I am trying to do an onclick delete on selected dynamic elements but for some reason it only selects the first element every time.
// Function to delete entries
$("#timesheet").on('click', '.delRow', function () {
const firstUrl = "API LINK..."
const secondUrl = document.getElementById("timesheetDetailsID").innerText
console.log(secondUrl)
const settings = {
"async": true,
"crossDomain": true,
"url": JSON.stringify(firstUrl + secondUrl),
"method": "DELETE",
"headers": {
"Content-Type": "application/json"
},
"processData": false,
success: function () {
alert("Yay")
},
error: function () {
//error handler
alert("Boo")
}
};
$.ajax(settings).done(function (response) {
console.log(response);
});
});
Example of the HTML page:
Example of the HTML
//Dynamic HTML
const htmlTemplate = `
<tr id = "testDeleteTimesheet">
<td>${entry.hours}</td>
<td id = "timesheetDetailsID" style = "display: none;">${entry.timesheetDetailsId}</td>
<td>${chartDate}</td>
<td>${entry.contractCode}</td>
<td>${entry.activityCode}</td>
<td>${entry.otFlag}</td>
<td>${entry.notes}</td>
<td><button id="edit-" + counter + "" class="btn editRow btnStyle btn-primary btn-sm"><span class= "bi bi-pencil"></span></button>
<button id="delete-" + counter + "" class="btn delRow btnStyle btn-danger btn-sm"><span class="bi bi-eraser"></span></button></td>
</tr>
`;
This is my static html where the dynamic content targets
//.html page
<table class="table" id="timesheet">
<thead>
<tr>
<th scope="col">Hours</th>
<th scope="col">Date</th>
<th scope="col">ContractCode</th>
<th scope="col">Activity Code</th>
<th scope="col">OT</th>
<th scope="col">Notes</th>
<th scope="col" id="rowBtns"></th>
</tr>
</thead>
<tbody id="tsdata"></tbody>
</table>
3
Answers
If you have more timesheets, you have to use class instead ID.
You are re-using the same
id
value multiple times in your HTML. If you have multiple elements withid="timesheetDetailsID"
then which element do you expectdocument.getElementById("timesheetDetailsID")
to return and why? Since IDs are supposed to be unique, the browser stops looking when it finds one.Use a
class
instead of anid
:Then in your click handler, traverse the DOM from
$(this)
to find the element you want for that specific row:This will start at the clicked element, use
.closest()
to traverse up to the parent<tr>
element, then use.find()
to traverse back down to the intended<td>
element, then get that element’s text.Below is a working example: