1

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!

2 Answers 2

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

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.