Could the onclick () function not have the same name as the calling element?

So I had this button element refusing to fire the onclick () function no matter what I did, and it drove me crazy for a while:

<button type="button" id="newTreatment" name="newTreatment" onclick="newTreatment()" >Add a treatment</button>

      

I ended up just changing the name of the function and it worked immediately:

<button type="button" id="newTreatment" name="newTreatment" onclick="addTreatment()" >Add a treatment</button>

      

I have since tested it on a few other buttons and have had similar problems all along.

So is this really what's going on? The onclick () function cannot have the same name as the ID if its an element? Why is this? I tried to search for this on the internet, but I could not find any information on it.

+3


source to share


2 answers


Inline event handlers are magical (i.e. not intuitive).

Inline element properties <form>

are located in the scope of inline event handlers. And since the name of each form control becomes a property of the form element, using that name inside an event handler will refer to that element.

The inline handler's scope chain is roughly equal to:

Global scope / properties of window
^
|
Properties of document (e.g. body)
^
|
Properties of enclosing form (e.g. newTreatment or submit)
^
|
Properties of <button id="newTreatment" /> (e.g. type, onclick)
^
|
Function scope of inline event handler

      



Snaps in wider areas (like in a shape) snaps to shadow images in higher areas, for example. Global coverage.

A simple solution would be to explicitly reference the global variable via window.newTreatment

.

I have described this in more detail here .

This seems to be framed in the HTML5 spec .

+4


source


Assuming you have your elements wrapped in form

, this is because named elements are added as properties in form

.

A newTreatement

property already existed in this area when you tried to call newTreatment

. He thought you meant a property and gave you an error



newTreatment is not a function

See Why does JS function name conflict with element id? and Do DOM tree elements with IDs have global variables?

+6


source







All Articles