Reputation: 14250
I am trying to assign an change event to an element. I have
var testDiv=getElementById('testDiv');
var SelectMenu=document.createElement('select');
SelectMenu.id='SelectMenu';
SelectMenu.onchange=changeFuntion();
testDiv.appendChild(SelectMenu);
function changeFuntion(){
//it calls right after I load the page....
alert('call');
}
html
<div id='testDiv'></div>
I want the alert shown only when user change the dropdonw menu. However, it seems the alert is called right after the element is created. Any tips? Thanks a lot!
Upvotes: 1
Views: 44
Reputation: 3709
You are assigning the return value of the function changeFunction
to SelectMenu.onchange
, rather than the function itself. Try...
SelectMenu.onchange = changeFuntion;
Instead. The way you had it, i.e.:
SelectMenu.onchange = changeFuntion();
means: call the function changeFunction
, and assign the return value to the SelectMenu.onchange
property.
Upvotes: 1
Reputation: 55740
SelectMenu.onchange=changeFuntion(); <-- This calls the function
^^--- Remove the braces
supposed to be
SelectMenu.onchange=changeFuntion ; <-- This assigns the function pointer
Because of the braces the function is called immediately...
Upvotes: 2