1

I found something strange when working with onclick to call a function. Let's say I have an input of type checkbox(it can be almost any type of input), with a name attribute and an onclick attached to it, calling a function:

function myFunction() {
    alert("Hello World");
}
<form action='' method='post'>
      <input type='checkbox' name='myFunction' onclick="myFunction()">
</form>

You can see that when the name of the input and the name of the function are the same I get TypeError: myFunction is not a function.

But when they are different the function call works well. I couldn't find any documentation about this anywhere. Can someone shed some light on this?

function myFunction() {
    alert("Hello World");
}
<form action='' method='post'>
      <input type='checkbox' name='testName' onclick="myFunction()">
</form>
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69

1 Answers1

2

As per the spec

A control's "control name" is given by its name attribute. The scope of the name attribute for a control within a FORM element is the FORM element.

So, the name's scope is changed inside a FORM, just a like a variable's scope is changed when declared again inside a function.

Try this without a Form

function myFunction() {
    alert("Hello World");
}
      <input type='checkbox' name='myFunction' onclick="myFunction()">
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • I've also knew about that. But it does not seem a solution to the main problem. Also, I didn't downvoted your answer. – Ionut Necula Oct 05 '16 at 12:37
  • @Anonymous this answer isn't as clear as it could be, but it does describe the problem. When the browser builds the event handler function, it puts the `
    ` object in the scope chain and that's why the element name hides the global function.
    – Pointy Oct 05 '16 at 12:42
  • @Pointy, agreed, but I don't think my question is a duplicate of the question that Quentin says it is. There is another function involved called clear(). [This link](http://stackoverflow.com/questions/9158238/why-js-function-name-conflicts-with-element-id/#answer-9160009) seems to explain everything. – Ionut Necula Oct 05 '16 at 12:46
  • @Anonymous it is a duplicate. The `
    ` object has properties corresponding to the various field names in the form. That object is injected into the scope of the function constructed from the text of the "onclick" attribute, so the field name will hide the global function name. If you were to assign the event handler with `addEventListener()`, then that scope thing would not happen and there would be no problem.
    – Pointy Oct 05 '16 at 12:49