I am using the jquery datatable with ajax call to fetch the data. I am trying to add the delete button so whenever the delete button is clicked I can get the ID of clicked row. But yet my code is just picking up the first ID of the row. Here is my code
<script type="text/javascript">
var table = $('#table1').DataTable( {
dom: "Bfrtip",
ajax: {
url : "http://localhost/cokeinventory/rest-api/api-search-stockin.php",
dataSrc: "doc",
},
columns: [
{ data: 'stock_id'},
{ data: 'item_name'},
{ data: 'unit' },
{ data: 'stockin_qty' },
{ data: 'barcode_number' },
{ data: 'barcode_label' },
{ data: 'balquantity' },
{
data: null,
className: "dt-center editor-delete",
orderable: false,
"mRender" : function ( data, type, row ) {
return '<button class="btn btn-success" id="deletebtn" value=' +data.stock_id +' >Delete <i class="fe fe-delete"></i></button>';
}
}
],
});
$("body").on("click", "#deletebtn", function(){
var val = $("#deletebtn").val();
alert(val);
});
});
</script>
3
Answers
Expanding on @Rory his comment. An id has to be unique, so you’ve to use classes instead.
So first change this line (The important piece here is that I removed the id, and added it in the class list):
And next for the jQuery, you’ve to change it into the following:
First, you have to assign a class to the button i.e
".deletebtn"
Why you should assign class selector rather than id for this scenario?
Because “id” is unique in a page and can only apply to at most one element, while “class” selector can apply to multiple elements. In your case, you have multiple buttons so class is the best approach in your scenario.
After that use
$(this).val()
to get the clicked button value.And for jQuery selector. You should use this script.
Use
class
instead ofid
as given below: