I have dynamically created rows and would like any row to be deleted accordingly.
var markup = "";
markup += '<tr>';
markup += '<td>' + result.data[0].firstName + result.data[0].lastName + result.data[0].jobTitle+ result.data[0].email + '</td>';
markup += '<td><button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editPersonnelModal" data-id = '+result.data[0].id+'> <i class="fa-solid fa-pencil fa-fw"> </i></button><button type="button" class="btn btn-primary btn-sm deletePersonnelBtn" data-bs-toggle="modal" data-bs-target="#deletePersonnelModal" data-id= '+ result.data[0].id+ '> <i class="fa-solid fa-trash fa-fw"></i> </td>';
markup += '</tr>';
$("table tbody").append(markup);
$('#deleteRow').on("click",function(){
var index = $('table tr').index();
alert(index)
});
The index value keeps showing 0 for all the rows and not its corresponding value, any help would be appreciated.
3
Answers
First of all, you can not use the same
id
value repeatedly in HTML. So useclass
for thisConvert
id="deleteRow"
toclass="deleteRow ...<other classes if any>"
Now Use
.closest()
to get the indexNote: if you want to remove that particular
<tr>
from HTML then directly use$(this).closest("tr").remove()
Working snippet:
Use
closest
and make sure you spell the ID/classNames correctly.In this code we do not need the ID to delete
i don’t find the id ‘deleteRow’ in the code
for the index() function, please refer to jQuery : https://api.jquery.com/index/
This example will help you :
If we retrieve one of the three list items (for example, through a DOM function or as the context to an event handler), .index() can search for this list item within the set of matched elements:
Result => Index: 1
So for your problem i see something like :
NB : i prefer debugging with console.log : console.log("index", index);
NB2 : don’t forget 0 is the value for first index
Keep me informed if it helped 🙂
Regards