Andy Andy - 24 days ago 7
PHP Question

Editable row in a table - is using the record ID on a <tr> element bad practice?

I'm trying to make a feature using jquery to edit a HTML table of category names.

So far I have my table being populated using PHP/MySQL. This all works ok.

I've read jQuery - Edit a table row inline but that doesn't seem to solve the issue of how you would identify a record if you wanted to save it back to a database.

I've seen solutions that do things like this:

<tr id="2">
<td>Foo</td>
</tr>
<td id="3">
<td>Bar</td>
</td>


Is this approach of using ID's on the
tr
element acceptable? It seems somehow backward, as this isn't really how I understand ID's should be used within markup? For example if you had multiple tables (not that I do in my case) all the ID's within markup should be unique so that would be bad practice?

Are there better approaches to dealing with this?

Just for some background information, this is what I'm looking to achieve:


  1. The table is rendered on page load.

  2. Click an 'Edit' button on a table row.

  3. This turns the row editable - I believe something similar could be used to the link I posted.

  4. Change the 'Edit' button to say 'Save'. Clicking this triggers an ajax call, but this would need to post the row ID and textbox value back to my PHP script.



The data is relatively simple - there is only an ID and category name per table row.

Answer

What you should be looking into is data attributes.

How you use them is ..

<tr data-id="2">
 <td>Foo</td>
 ....
</tr>
<tr data-id="3">
 <td>Bar</td>
 ....
 </td>

And lets say you need to get the id of a clicked row, you can do so by using .data() method.

...
$(tr).on('click', function(){
 id = $(this).data('id');
 ...
});
...
Comments