0

I'm having a problem referencing a global variable inside an object literal:

function f() {
    globalVar = "test";
}

$(document).ready(function() {
    f();
    var a = $("#id").autocomplete({ 
        lookup: globalVar //says globalVar is undefined
    });
    $("#button").click(function() {
        alert(globalVar); //works
    });
});

How can I set the value of lookup to globalVar?

3
  • Is this your actual code? There's no reason globalVar would be defined in the alert(), but undefined for the property value assignment. Commented Sep 12, 2011 at 3:33
  • What browser(s) did you test in? Commented Sep 12, 2011 at 3:56
  • @patrick You're right, the alert is actually in a click event as shown. The alert did not work how I had it, but it definitely works as it is now. Commented Sep 12, 2011 at 4:05

2 Answers 2

1

you can define it outside all functions like this;

var globalVar ;

function f() {
    globalVar = "test";
}

$(document).ready(function() {
    f();
    alert(globalVar); //works
    var a = $("#id").autocomplete({ 
        lookup: globalVar 
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

There is no reason that shouldn't work, it either has to do with a misunderstanding on how to use that autocomplete function, or a problem in the function itself. But the global should be assigned, and there is no problem assigning a global to an object that way. Either way, without more code (i.e. that autocomplete function), can't say what the issue is.

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.