Lord Vermillion
Lord Vermillion

Reputation: 5424

Change javascript variable with jquery

In my MVC project i import a .js file in my shared layout.

 <script src="@Url.Content("~/Scripts/bootbox.js")" type="text/javascript"></script>

This file has this variable

var locales = {
            en: {
                OK: "OK",
                CANCEL: "Nej",
                CONFIRM: "Ja"
            }}

In one of the views i would like to change the OK value for en with jQuery. How can i do this?

Upvotes: 0

Views: 191

Answers (2)

AmericanUmlaut
AmericanUmlaut

Reputation: 2837

Assuming the file defines locales as a global variable,

locales.en.OK = 'en';

To be clear, though, this has nothing to do with jQuery, razor, or model-view-controller. It's simply how you set the property of an object in native Javascript, there's no further technology required to do this.


I have now downloaded bootbox.js myself to look at what's going on here. locales is not defined as a global variable, it's scoped to the anonymous wrapper function that contains all of the contents of bootbox.js.

This means that there is no way to change the contents of that variable dynamically from outside of that scope. If you want to permanently change that text, then you can change it in bootbox.js manually. If you want to change it dynamically, then you can replace

var locales = ...

with

window.locales = ...

in bootbox.js, and then use my original suggestion in your own code.

Upvotes: 2

Rashmin Javiya
Rashmin Javiya

Reputation: 5222

You may declare locales in some scope, define locales outside of scope that is global or just remove var from locales as mentioned below.

locales = {
  en: {
    OK: "OK",
    CANCEL: "Nej",
    CONFIRM: "Ja"
}}

You can call it by locales.en.OK

Upvotes: 0

Related Questions