Binding to the change event in dynamically created dropdown list using jQuery
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 triggere开发者_StackOverflowd 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.');
});
}
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.
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.');
});
精彩评论