Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change event on <select> not firing in IE

I've got a page with a variable number of <select> elements (which explains why I'm using event delegation here). When the user changes the selected option, I want to hide/show different content areas on the page. Here's the code I have:

$(document).ready(function() {
  $('#container').change(function(e) {
    var changed = $(e.target);

    if (changed.is('select[name="mySelectName"]')) {
      // Test the selected option and hide/show different content areas.
    }
  });
});

This works in Firefox and Safari, but in IE the change event doesn't fire. Anyone know why?

like image 518
Justin Stayton Avatar asked Oct 28 '09 14:10

Justin Stayton


4 Answers

The change event does not bubble in IE (See here and here). You cannot use event delegation in tandem with it.

In fact, it is because of this IE bug that jQuery live had to officially exclude change from the list of supported events (FYI the DOM spec states change should bubble).[1]

With respect to your question, you can bind directly to each select:

$('#container select').change(/*...*/)

If you really want event delegation you might find some success trying what this person did and bind to click in IE only, which does bubble:

$('#container').bind($.browser.msie ? 'click' : 'change', function(event) {
    /* test event.type and event.target 
     * to capture only select control changes
     */
})

But this browser detection feels really wrong. I'd really try working with the former example (binding directly to the drop downs). Unless you have hundreds of <select> boxes, event delegation wouldn't buy you much here anyway.


[1] Note: jQuery >= 1.4 now simulates a bubbling change event in IE via live()/on().

like image 76
Crescent Fresh Avatar answered Nov 03 '22 23:11

Crescent Fresh


Idea that might help:

$(document).ready(function() {
  $('#container select[name="mySelectName"]').change(function(e) {
    var s = $(e.target);
    if (s.val()=='1') //hide/show something;
  });
});

If you are using AJAX, try live() function:

 $(document).ready(function() {
       $('#container select[name="mySelectName"]').live('change', function(e) {
        var s = $(e.target);
        if (s.val()=='1') //hide/show something;
      });
    });
like image 22
Arnis Lapsa Avatar answered Nov 04 '22 01:11

Arnis Lapsa


If I recall correctly you will need to call blur() to have jQuery invoke change() on IE machines. Try something like:

$("select[name=mySelectName]").click(function() {
    $(this).blur();
});
like image 3
Daniel Sloof Avatar answered Nov 04 '22 01:11

Daniel Sloof


using jquery 1.4.4 (and i think 1.4.3) seems to be all good now.... the change event works consistently in my limited testing.

like image 3
user406905 Avatar answered Nov 04 '22 01:11

user406905