I\'m adding select elements dynamically, like in the below HTML. I\'m not sure why the .on(\'change\' ...) is not working for the dynamic select. What am I missing?
< $('#tablecontent').on('change', '#tablecontent > table.CampaignGrid > tbody > tr > td', function(e) {
console.log('IN TABLE CONTENT CHANGE');
var value = e.target.value;
$('button#updateLuck').prop('disabled', false).css({'color': '#000', 'font-weight': 600});
//alert($(ele[0]).html());
});
$('#tablecontent').on('change', '#tablecontent > table.CampaignGrid > tbody > tr > td', function(e) {
console.log('IN TABLE CONTENT CHANGE');
var value = e.target.value;
$('button#updateLuck').prop('disabled', false).css({'color': '#000', 'font-weight': 600});
//alert($(ele[0]).html());
});
$('#tablecontent').on('change', 'table.CampaignGrid > tbody > tr > td', function(e) {
console.log('IN TABLE CONTENT CHANGE');
var value = e.target.value;
$('button#updateLuck').prop('disabled', false).css({'color': '#000', 'font-weight': 600});
//alert($(ele[0]).html());
});
$('#tablecontent').on('change', '#tablecontent > table.CampaignGrid > tbody > tr > td', function(e) {
console.log('IN TABLE CONTENT CHANGE');
var value = e.target.value;
$('button#updateLuck').prop('disabled', false).css({'color': '#000', 'font-weight': 600});
//alert($(ele[0]).html());
});
Your event binding is set on $(document).ready(). However, if you are dynamically adding them later (like via jQuery.appendTo() or the like), the newly added components need to be binded since they were not part of the inital one that happened in $(document).ready(), which only runs once when the page is loaded and the DOM is initially done.
Correct syntax:
$('#x').on(
'change',
'select',
function () {
alert('helo');
}
);
So syntax of on()
for dynamic element seems:
$(staticParent).on( eventName, target, handler);
Came across this as I could not get my dynamically created selects which came back from an ajax post with dynamic id's, to trigger the event.
$(document).on('change', 'select', function (e) {
$("#theDiv select").on("change",function(){ post("SelectChanged");} );
});
This would not work until I had changed something first so I added
$("#theDiv select").on("change",function(){ post("SelectChanged");} );
However this not meant, that after the change, all other changes then fired twice. This may not be very good practice. But what I did was to to put in a function that is called at the start and each return of ajax.
`function myFuncs(){
$('#theDiv select').unbind('change');
$('#theDiv select').on('change' function(){ post('selectChanged'); });
}`
But had to unbind at start of each function call else it doubled up the functions each time. I am sure there must be a proper way to do this, I just haven't found it yet. Thanks for starting the question.