views:

46

answers:

2

I am creating a number of dropdown lists dynamically using jQuery. I would like to be able to trigger an event when the selected dropdown list item changes. From browsing on here and elsewhere I see that it's not possible to bind to the change event of the dropdown lists using live() so I am wondering what are the alternatives? I know it's possible to bind to the click event but since that occurs before the dropdown list selection can change it's no use to me for tracking if the selected item has changed.

This is the relevant part of my code. The alert triggers when any of the dropdown lists are clicked on but of course I would prefer if the alert was triggered only when the selected item is changed.

$(document).ready(function() {
    // Stuff omitted.
    addEventHandlers();
}

function addEventHandlers() {
    // Stuff omitted.
    $('#divReview select').live("click", function(){
        alert('This is where I would like the change event to occur instead.');
    });
}
+2  A: 

Use the change event instead of click, like this:

$('#divReview select').live("change", function(){

There was a bug in IE specifically before the jQuery 1.4.2 release. Before then, change didn't bubble correctly in IE (which .live() relies on), this was fixed in 1.4.2, so if using that version or higher, this should work.

Nick Craver
Thanks for that Nick. I am using jQuery 1.4.2 and I've tested replacing 'click' with 'change' on Chrome and Firefox 3.6.10 and it works but unfortunately not on IE8.
Malice
A: 

After a bit of searching I came across this question which seems to be a similar issue. I changed my jQuery method to this and it works as expected on IE8:

$('body').delegate('#divReview select', 'change', function() {
    alert('Change event triggered.');
});
Malice