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>

1
  • perhaps because it resolves to the element instead of a global function. Commented Oct 5, 2016 at 12:30

1 Answer 1

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()">

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

4 Comments

I've also knew about that. But it does not seem a solution to the main problem. Also, I didn't downvoted your answer.
@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 <form> object in the scope chain and that's why the element name hides the global function.
@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 seems to explain everything.
@Anonymous it is a duplicate. The <form> 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.