views:

217

answers:

1

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?

+4  A: 

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');
}
Pointy
'doh! Of course! Thanks!
DA