Wednesday, June 13, 2018

unable to fetch the id of dynamically generated button in jquery











        $(document).ready(function(){
$('#btn').click(function(){

var createInput=$("");
createInput.attr("id","close1");

createInput.attr("value","close");
$('#outer-div').append(createInput);
});

$("#close1").click(function(){
alert('hi');
});
});











What's wrong with the code. I am not getting the alert when i click the dynamically generated button named as close. Please help it out


Answer




This would work :



    $(document).ready(function(){
$('#btn').click(function(){

var createInput=$("");
createInput.attr("id","close1");
createInput.attr("value","close");
$('#outer-div').append(createInput);
});


$(document).on('click', "#close1", function(){
alert('hi');
});
});


The problem with



$("#close1").click...



is that it adds an event handler to nothing, as the collection is empty when you execute this line. The on function fixes that.



BTW, it's recommended to put your script at the end of the body instead of in the head.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...