Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

target a button inserted by ajax with javascript

hello i'm inserting this image with a button by ajax when visitor upload an image

for (var i = 0; i < data.length; i = i + 1) {
    imageThump += '<img src="' + data[i].path + '" />';
    imageThump += '<button id="edit-details" type="button" class="btn btn-info">Edit Details</button>';
}
$('#uploaded-images-thumb').append(imageThump);

i want to target the button with javascript but it keeps failing ???

$('#edit-details').on('click', function(){
    console.log('clicked');
});
like image 440
user3266289 Avatar asked Mar 01 '26 02:03

user3266289


1 Answers

You need to deal with dynamic event (aka live event). As the button injected into DOM after DOM load.

$('body').on('click', '#edit-details', function(){
    console.log('clicked');
});

NOTE: instead of body, should bind to its closest non-dynamic parent element. If your #uploaded-images-thumb is non-dynamic then better to bind against it. like:

$('#uploaded-images-thumb').on('click', '#edit-details', function(){
    console.log('clicked');
});

For more detail check .on()

like image 141
thecodeparadox Avatar answered Mar 03 '26 15:03

thecodeparadox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!