Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my function is not a function?

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?

like image 278
Mr.Rendezvous Avatar asked Apr 18 '12 04:04

Mr.Rendezvous


2 Answers

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...

    • has the same name as any property on the element with the handler, or
    • has the same name as any property on the 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>

like image 184
4 revs, 3 users 69% Avatar answered Sep 17 '22 23:09

4 revs, 3 users 69%


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 />
like image 39
NemyaNation Avatar answered Sep 19 '22 23:09

NemyaNation