Joe Strommen
Joe Strommen

Reputation: 1234

jQuery change event not firing in IE8 on multiple <select> when more options are selected

I'm trying to create a multi-select list and do some stuff when the selection changes. I have the following code in an ASP.NET MVC view (Model.AvailableChoices is an IEnumerable):

@Html.ListBoxFor(
m => m.Value,
Model.AvailableChoices.Select(s => new SelectListItem() {Text = s, Value = s,})
, new {@class = "StringChoiceMetadataFieldViewModel"}
)

It generates the following html:

<SELECT id="MetadataFields_10__Value" name="MetadataFields[10].Value" multiple="multiple" >
  <OPTION value="Wakka">Wakka</OPTION>
  <OPTION value="Splat">Splat</OPTION>
  <OPTION value="Bang">Bang</OPTION>
</SELECT>

And I'm binding to the change event via jQuery (v1.6.4):

$('#someDivAboveTheSelect select').change(function () {
alert('change event');
}); 

The change event handler is not getting hit when I ctrl+click to change the selection, unless I do something that causes the first selection in the list to change. So if I select Wakka then ctrl+click Splat I don't get the event. However if I select Splat then ctrl+click Wakka I do.

Normal click changes work just fine. And everything works just fine in Chrome and Firefox.

Does anybody know what's going on here? I suspect it might be something about needing IDs on the select options...if that's the case, how do I make that happen with MVC?

Thanks

Upvotes: 3

Views: 1505

Answers (2)

Jrud
Jrud

Reputation: 1004

Wow this is really an issue...

If you don't figure out a cleaner solution to this here's what you do:

  1. Use the .click event instead of .change and compare the last selection with the current one to simulate "change" functionality
  2. Submit a bug report to Microsoft & demand they fix IE

~~~~~~~~~~~~~~~Append~~~~~~~~~~~~~~~

After thinking about why this problem is the way it is, the only reason of why IE behaves the way it does, is that there is a coder somewhere out there in a big building in a cubicle that, while writing the event handler code in IE, wrote some code similar to this:

Selection = HookedSelect.FirstSelectedElement;
If (Selection != LastSelection)
{
    LastSelection = Selection;
    Raise Event Change(Selection);
}

Upvotes: 0

karim79
karim79

Reputation: 342635

I wonder if this will help:

$('#someDivAboveTheSelect select').change(function () {
    alert('change event');
});

// blah blah use feature detection instead
// in reality, sometimes browser hacks are needed
// not quite sure about this case, though
if($.browser.msie && parseInt($.browser.version, 10) === 8) {
    $('#someDivAboveTheSelect select').click(function () {
        $(this).trigger("change");
    });
}

Upvotes: 2

Related Questions