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 id
is the same as the function name(toggle_SITEID
).
In Internet Explorer, using an element's id
is a shortcut for document.getElementById()
. Break the link by using a var
declaration.
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...
document
Since 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 global foo()
unless we've done something like document.foo = "bar"
. Since the document
is injected as a variable object in the scope chain, the document.foo
now shadows the global foo
.
Same goes with the element itself. If we add the foo
property to the element before invoking the global function, that property will shadow the global. <a onclick="this.foo = 'bar'; foo();">click me</a>
The error for me was the the ID was the same name as the function.
Change the id to something else different to the function name you aim to call on-click.
Change
<input type="checkbox" id="toggle_SITEID" name="@@toggle_SITEID" onclick="toggle_SITEID(this)" /> New <br />
To:
<input type="checkbox" id="toggle_SITEID" name="@@toggle_SITEID" onclick="toggle_SITE_ID(this)" /> New <br />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With