Reputation: 101
I am working on a permissions page on my site and currently have it sets up with three columns Username
Permissions
and Action
. When I press the Edit
button in the Action
column I want to be able to edit the Permissions
column only in that specific row. Right now I have it setting both the Username
and Permissions
cell to be contenteditable.
Here is is my definition of my table (data being pulled from DB):
echo "<td class='username'>" . $row['username'] . "</td>";
echo "<td class='permissions'>" . $row['isAdmin'] . "</td>";
echo "<td><input type='button' class='btn btn-primary edit' value='Edit'></td>"
And Here is the script I am currently using to change each column in the row:
var $this = $(this);
var tds = $this.closest('tr').find('td').filter(function () {
return $(this).find('.edit').length === 0;
});
//console.log(tds);
if ($this.val() === 'Edit') {
$this.val('Save');
if($this.id !== '.edit') {
tds.prop('contenteditable', true);
}
}
I need it to only select the <td class='permissions'>
in the current row that the button was clicked on.
What is the proper way to select only that cell in the corresponding row?
I've tried multiple ways to try and only select it from tds based on the class but have had no success.
Upvotes: 0
Views: 669
Reputation: 28196
Instead of using the rather complicated construction
var tds = $this.closest('tr').find('td').filter(function () {
return $(this).find('.edit').length === 0;
});
you could simply do
var tds = $(this).closest('tr').find('td.permissions');
to identify the target element to make editable. I assume that this code is part of the 'click'-event function for the "edit" button..
Upvotes: 1
Reputation: 383
I have made a fully editable HTML Table using DataTables and some custom code. I can't share the whole code though, as it is a closed-source project for work, but I think it will be helpfull.
Some useful notes:
1) I used Mutation Observer Api to track changes in cell values. I stored every changed cell in an array and on clicking 'Save' the array gets sent with AJAX to the back-end.
2) There is a HTML attribute called contenteditable. It lets you edit, well, the content of an element. Use that to edit the cells' values before appending them to the array. Attach an event listener to the 'Edit' button and when it is clicked, add this attribute to all the 'td' elements of your table.
3) You just send the array with values to the back-end and run some simple queries to your database.
Hope it helps you.
Upvotes: 0