2

JavaScript:

 lang = {'edit': 'Edit'}; // global variable

HTML:

 <select onchange="alert(lang.edit)"> // alerts undefined 

Whenever the event fires, it alerts "undefined". The lang variable is global, so why can't the inline event handler code reference it?

1
  • 5
    There is no JSON there, just a regular object (and the syntax still wouldn't be JSON if you took it out of the JS, JSON uses double quotes only). There's no reason in your question for it not to work, the problem is likely elsewhere. Commented Dec 11, 2010 at 19:52

2 Answers 2

4
  1. Make sure that the JavaScript file is explicitly setting a global variable:

    window['lang'] = {'edit': 'Edit'};
    
  2. Make sure your event handler code explicitly refers to the global "lang" variable:

    <select onchange='alert(window.lang.edit)'>
    

The 1st one is probably already OK, but I add that just to make sure. The second thing, well, the interpretation of "onfoo" attribute values is subtle and weird. If there's a "lang" attribute of the <select> DOM element or a "lang" attribute on a <form> tag surrounding the <select>, then a reference to the identifier "lang" in the "onclick" value will pick up that instead of the global "lang" you define in the JavaScript file. Your "onclick" value is turned into a function (in order for it to work as an event handler) by a process that looks more-or-less like this:

var handler = new Function("event", "with (this.form) { with (this) { alert(lang.edit); }}");

It's weird, but that's actually what happens with that sort of event handler code.

Sign up to request clarification or add additional context in comments.

2 Comments

problem solved .. but may i ask why it isn't reachable from event call ? also i tried this $lang.edit and the object was $lang = {...} .. this way relates to jQuery which i am using this project .!?
When you used "$lang" as the variable name, did it work? Also, what does the rest of the Javascript around that "lang" declaration look like?
0

Every global object in javascript is a property of the window object. So you should write window.lang = {'edit': 'Edit'};

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.