Reputation: 1208
i'm trying to catch a change() on a select which is added after the dom generation but i can't success. Here is a sample code:
HTML:
<div class="test" id="divTest"></div>
jQuery:
$('#divTest').click(function(){ $(this).parent().append("<select id='testSel'><option value='f'>F</option><option value='F'>D</option></select>");});
$('#testSel').change(function(){
alert('change');
});
I want to see the alert when i change the value in the select..
And here is a fiddle. http://jsfiddle.net/T8J8p/3/
Upvotes: 2
Views: 2116
Reputation: 128791
Two problems:
select
element's ID is #testS
not #testSel
.1on()
method:$('body').on('change', '#testS', function(){
alert('change');
});
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
1. This related to original JSFiddle featured in the question (available here). The question has since been edited.
Upvotes: 5
Reputation: 2176
$('#divTest').click(function(){
$(this).parent().append("<select id='testS'><option value='f'>F</option><option value='F'>D</option></select>");
$('#testS').change(function(){alert('change');});
});
You can't bid to something that does not exist yet, so bind it after the click, inside the function. And there was a typo in the selector #testS vs #testSel
Upvotes: 0
Reputation: 62488
You have to bind event using event delegation as the element is added to the DOM after the DOM loaded:
$(document).on('change','#testSel',function(){
alert('change');
});
See Details HERE
Upvotes: 0
Reputation: 5222
Try this,
$('body').on("change", "#testSel", function(){
alert('change');
})
Upvotes: 1
Reputation: 82241
You need event delegation dynamically added DOM::
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(document).on('change','#testS',function(){
alert('change');
});
Upvotes: 3