I have a jQuery Datatable and I dynamically add rows. Each row has a cell in which there's a delete button. My problem is that I can't get to delete the rows with the buttons and I can't even manage to target the current row.
Here's my DataTable code :
var tab_presta = $("#tableau_presta").DataTable({
"searching": false,
"paging": false,
"ordering": false,
"info": false,
responsive: true,
"language": {
"emptyTable": "No product added to the contract for the moment."
}
});
Here is how I create the buttons on each row (on a submit event) :
form2.on('submit', function (event) {
tab_presta.row.add(
[
'<center><button type="button" id="btn_supp' + (++idCount) + '" onclick="alert(this.parentNode)" class="btn btn-xs btn-block btn-danger confirmation">Delete</button></center>'
]
)
.draw( false );
// here I dynamically add an id to each button based on a variable
$('.btn btn-xs btn-block btn-danger confirmation').each(function() {
$(this).attr('id', 'suppr' + idCount);
idCount++;
});
});
And here is my code for deleting when clicking on each button :
for (j = 0; j <= btn_count; j++) {
$("#tableau_presta").on("click", btn_supp[j], function(){
//tab_presta.row($(this).parents('tr')).remove().draw(false);
var row = $(this).closest("tr");
console.log(row);
});
}
As you can see I commented the remove() part because it doesn't work, so I tried to find the closest tr
of $(this) (button)
, but I don't get the row in the console as a result. It's empty and I don't understand why because the button actually exists and I can get its id when I click on it if I put a onclick"alert(this.id)
.
Any idea ?
You don't need to bind the click event inside of a loop. Instead, use a class
or an attribute selector . In this case, selecting all elements with an id
that ^
starts with btn_supp
= [id^=btn_supp]
.
$("#tableau_presta").on("click", "[id^=btn_supp]", function() { $(this).closest("tr").remove(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="tableau_presta"> <tr> <td> <button type="button" id="btn_supp1" class="btn btn-xs btn-block btn-danger confirmation">Delete</button> </td> </tr> <tr> <td> <button type="button" id="btn_supp2" class="btn btn-xs btn-block btn-danger confirmation">Delete</button> </td> </tr> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.