How to programmatically change a selection so that it works when it changes?

This does not work:

<select id="mySel" onchange="alert('foo')"> <option value="a">a</option> <option value="b">b</option> </select> <script> dojo.byId('mySel').value = 'b'; // select changes, but nothing is alerted </script> 

(I use dojo, but that doesn't really matter.)

+6
javascript select onchange
source share
6 answers

The name "onchange" is a little misleading if you do not understand that a change event and a mutable value are not the same thing. A change event occurs when a user changes a value in a browser. I believe that you can fire the event manually by calling dojo.byId('mySel').onchange() after you programmatically change the value. (You may need to actually define a function that calls alert . I have not done this myself.)

+6
source share

This will change the value, but will not fire the onchange event. Every time you change an element using JavaScript, it does not fire an event (it stops you from recursion problems *).

If you configured the event handler like this.

 function myHandler(){ //do whatever stuff here changeColor( dojo.byId('mySel') ); } 

then you can call it separately after you set the value programmatically.

Note (*): I am not a dojo expert ... so I assume that they did not "add" an automatic call to event handlers when you set the value from JavaScript.

+3
source share

You can take a look at these questions and their answers: they can help:

  • Detect software changes in the html selection window.
  • How can I programmatically force an onchange event on input? (focused on the input, not on it, but may be useful)
+2
source share

you can access the onpropertychange event, it contains the property in the event arguments to determine which property has been changed.

It detects the changes of "selectedIndex" and "value" - just a case test "propertyName"

 <select id="mySel" onpropertychange="dothis(event);"> <option value="a">a</option> <option value="b">b</option> </select> function dothis(event) { if (event.propertyName == "selectedIndex") alert('selection changed'); } 

from the top of my head ... (currently using the asp.net js framework, which is pretty different)

+1
source share

Try assigning selectedIndex instead.

0
source share

For those who want to fire the change event using javascript.

  var evObj = document.createEvent("HTMLEvents"); evObj.initEvent("change", true, true); var elem = document.getElementById('some-id'); elem.dispatchEvent(evObj); 
0
source share

All Articles