jQuery change event on select isn't being triggered via other function changing selected attribute

StackOverflow https://stackoverflow.com/questions/2321408

  •  22-09-2019
  •  | 
  •  

Question

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

That, as is, works. If I click an item in the multiselect, the alert is triggered.

However, when I 'select' an element from the select menu via jQuery like so:

$('#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");
        }
    })

That script works in that it changes the SELECTED attribute and visually updates the option list, however the onchange event doesn't get triggered in that scenario.

Why is that?

Was it helpful?

Solution

Changing elements with code like that just doesn't trigger event handlers. You can do it yourself however:

else {
  $matchingOption.attr('selected', 'selected').trigger('change');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top