I want to update a record using AJAX, but when I click the button to edit
the row I get the same data-id
of the first row in the table
element.
<table>
<!-- this data inside php foreach loop displayed via ajax -->
<tr>
<td> <a href="<?= $row->id; ?>" id="edit_btn" data-id="<?= $row->id; ?>">edit</a></td>
<td> <a href="<?= $row->id;?>'" id="delete_btn" data-id="<?= $row->id; ?>">delete</a></td>
</tr>
</table>
$(function($) {
edit();
})(jQuery);
function edit() {
$(document).on('click', '#edit_btn', (e) => {
e.preventDefault();
var aid = $('#edit_btn').attr('data-id');
// var aid = $('#edit_btn').data('id');
alert(aid);
});
}
3
Answers
You should retrieve the data-id using the data method:
Warning
ID’s Must Be Unique, specifically because it will cause problems in JavaScript and CSS when you try to interact with those elements.
The main issue in your code is because you’re giving all the elements in your loop the same
id
, which is invalid.id
attributes must be unique within the DOM. You should use a class instead to attach the event handlers, then use thethis
keyword within the event handler to get a reference to the element which raised the event. The latter point means that you need to remove the arrow function and use an anonymous one instead.That being said, there’s other issues in your code which need addressing. Firstly the document.ready event handler is not an IIFE. Remove
(jQuery)
from the end of it. In addition, usedata()
to retrieve data attributes, notattr()
. Lastly, don’t usealert()
for debugging as it coerces data types. Useconsole.log()
instead.If you’d prefer to use the arrow function then instead of
this
you would need to usee.target
:You can use
$(this)
inside the callback to manipulate only the clicked element