Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change event on select isn't being triggered via other function changing 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"));
    })

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?

like image 477
DA. Avatar asked Feb 23 '10 20:02

DA.


1 Answers

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');
}
like image 114
Pointy Avatar answered Nov 14 '22 21:11

Pointy