I have this in my view page:
<input type="checkbox" id="toggle_SITEID" name="@@toggle_SITEID" onclick="toggle_SITEID(this)" /> New <br />
then in my js file I have this:
toggle_SITEID = function (chk) {
// something
}
and then I click checkbox, “something” won’t run. I check in firebug console the error message was:
toggle_SITEID is not a function
So why is it?
There could be couple of reasons for this error:
You didn’t reference the script in the HTML file.
The function isn’t declared in the global scope but in an inner scope.
global scope- WORKING DEMO
inner scope – NON WORKING DEMO
There is an element whose
idis the same as the function name(toggle_SITEID).In Internet Explorer, using an element’s
idis a shortcut fordocument.getElementById(). Break the link by using avardeclaration.Another issue that can arise is when you have an inline handler that tries to use a global variable that interferes with the unique scope chain of inline handlers. That happens when the global…
documentSince the scope chain of an inline handler has the element itself, as well as the
document, injected into the scope chain as variable objects, any property on those objects will interfere when accessing global variables.For example, given this element:
<a onclick="foo();">click me</a>, we can successfully invoke the globalfoo()unless we’ve done something likedocument.foo = "bar". Since thedocumentis injected as a variable object in the scope chain, thedocument.foonow shadows the globalfoo.Same goes with the element itself. If we add the
fooproperty to the element before invoking the global function, that property will shadow the global.<a onclick="this.foo = 'bar'; foo();">click me</a>