For a dashboard where there is a list of links I want to perform some actions if someone clicks the delete button. But somehow it only responds on the first link with id=\"delet
In HTML Ids must be unique. If you have multiple elements, you should use classes.
echo "<span class='delete_link' data-linkid='" . $link->id . "' class='glyphicon glyphicon-remove'></span>";
Script, Use class selector to bind event
$('.delete_link').click(function(){
//Your code will work fine
});
use below code . assign class 'delete_link' to elements instead of id.
echo "<span style='float:right;opacity:0.85;' class='glyphicon glyphicon-pencil'></span><span style='float:right;opacity:0.85;margin-right:10px;' class='delete_link' data-linkid='" . $link->id . "' class='glyphicon glyphicon-remove'></span>";
id must be unique in a DOM. so event only work on i element who have same id.
also you need to check Event delegation to attach event to dynamically created element. 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).ready(function(){
$(document).on('click','.delete_link',function(){
var dataId = $(this).data('linkid');
var confirmDelete = confirm("Are you sure you want to delete this link?");
if(confirmDelete == true) {
alert(dataId);
// $.ajax({
// type: "POST",
// url: "delete_link.php",
// data: ""
// })
}else {
alert("FALSE");
}
});
});