Question

This doesn't seem to be working:

<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'm using dojo, but that doesn't really matter.)

Was it helpful?

Solution

The 'onchange' name is a little misleading unless you understand that a change event and a value being changed aren't the same thing. A change event occurs when the user changes the value in the browser. I believe you can fire the event manually by calling dojo.byId('mySel').onchange() after you programmatically change the value, though. (You might need to actually define a function that calls alert, though. I haven't done this myself.)

OTHER TIPS

This will change the value but not fire the onchange event. Any time you modify an element with JavaScript it will not fire the event (stops you from getting into recursion issues*).

If you set up an event handler like so.

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

then you can call this separately, after you set the value programatically.

Note (*): I'm not a dojo expert... so I'm presuming they haven't "added" the automatic calling of the event handlers when you set the value from JavaScript.

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

For anyone looking to trigger the change event using javascript.

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

you can access the event 'onpropertychange' it contains a property within the event arguments to identify which property was changed.

It detects both 'selectedIndex' and 'value' changes - simply 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');
}

off the top of my head... (currently using the asp.net js framework which is quite abit different)

Try assigning selectedIndex instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top