1

I am trying to set a javascript global var using jquery and dynamic variable names like this:

var home_phone_number // located outside of any functions
.
.
.
function setPhoneVars(phone){
// do stuff here to determine the correct prefix
thePrefix = 'home_phone_'
$(thePrefix + "number").val(phone.number);

}

When I do this, the value of home_phone_number is undefined.

But, when I set the phone number manually, like this:

home_phone_number = phone.number

the variable is set as expected.

3
  • 1
    Why do you think it would work? Commented Oct 22, 2012 at 19:40
  • why do i think it would work? I can directly assign the value from within the javascript function WITHOUT using jquery, that's why. Commented Oct 22, 2012 at 19:43
  • jQuery is a library, a collection of functions and It simply doesn't have a function (as far as I know) to set the value of a variable. $(thePrefix + "number") Will look for an HTML element like <home_phone_number> Commented Oct 22, 2012 at 19:53

4 Answers 4

12

Global variables are properties of the window object, so can be accessed as such:

window[thePrefix+'number'] = phone.number;
Sign up to request clarification or add additional context in comments.

3 Comments

that worked. Thanks. But still I wonder why the jQuery code did not, and is there a syntax change I could have made to make it work?
Because the jQuery code makes bugger all sense, that's why it didn't work.
bugger all sense. I like that.
1

You can access global variables through window object, e.g.

var home_phone_number = "value";

function setPhoneVars(phone) {
    var thePrefix = "home_phone_";
    window[thePrefix + "number"] = phone.number;
}

Comments

1

Instead of having such many globals.. you can use a single object..

var globals = {
   home_phone_number: 0 // located outside of any functions
} 


function setPhoneVars(phone){
  // do stuff here to determine the correct prefix
  thePrefix = 'home_phone_'
  globals[thePrefix + "number"] = phone.number;
}

2 Comments

Technically, by using global variables, you already are using a single object: window.
@Kolink True, I understand the above is additional wrapper.. but this I believe is is more like inside a group.. Something like window.pluginA.property and window.pluginB.property
0

I think your use of JQuery is not appropriate; .val() is intended to set the value of HTML elements, i.e. HTML objects in the DOM.

To simply set a dynamic JavaScript variable you could use eval() which is a JavaScript function which treats a string as executable code;

thePrefix = "home_phone_";
eval(thePrefix + "number = phone.number;");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.