How do I programmatically change a select so that

2019-02-13 17:39发布

问题:

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

回答1:

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



回答2:

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.



回答3:

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

  • Detect programmatical changes on a html select box.
  • How do I programatically force an onchange event on an input? (focused on input, and not select, but might still be useful)


回答4:

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)



回答5:

Try assigning selectedIndex instead.



回答6:

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);