JQuery change event on selection does not fire using another function that changes the selected attribute

HTML

<select multiple="multiple" id="myID" name="myName">
    <option value="blue">blue</option>
    <option value="red">red</option>
    <option value="green">green</option>                
</select>

JQuery

$('select')
    .change(function(){
        alert("Change Event Triggered On:" + $(this).attr("value"));
    })

This, as it is, works. If I clicked an item in the multi selector, a warning is triggered.

However, when I 'select' an item from the select menu via jQuery, for example:

$('#myOtherSelector')
    .click(function(){
        var $matchingOption = [goes and selects the specific OPTION to toggle]
        if ($matchingOption.attr("selected")){
            $matchingOption.removeAttr("selected")
        }else{
    $matchingOption.attr("selected","selected");
        }
    })

This script works so that it changes the SELECTED attribute and visually updates the list of options, however the onchange event does not fire in this script.

Why is this?

+5
source share
1 answer

Changing elements with this code simply does not trigger event handlers. You can do it yourself:

else {
  $matchingOption.attr('selected', 'selected').trigger('change');
}
+11
source

All Articles