Andy Andy - 1 month ago 5
jQuery Question

Targetting a <td> from it's parents <tr> with data-attributes using jquery

I'm developing an editable table feature as described in a previous post: Editable row in a table - is using the record ID on a <tr> element bad practice?

I've got the following markup:

<tr data-id="2">
<td>Foo</td>
<td><button class="editBtn">Edit</button></td>
</tr>
<tr data-id="3">
<td>Bar</td>
<td><button class="editBtn">Edit</button></td>
</tr>


Using jquery I've been able to work out which row I'm editing by targeting the
.editBtn
and then using the following to work out which is the
data-id
element:

$('.editBtn').click(function() {
id = ($(this).closest('tr').data('id'));
console.log(id);
});


What I don't understand is given this ID how can I then target the
td
element which has my category name in it (Foo and Bar, in this example)?

I want to be able to take the content in these and place them in an editable field thus:

<td><input type="text" value="Foo"></td>


I also need to be able to change the 'Edit' button to a 'Save' button at this point, with a different class name, e.g.

<td><button class="saveBtn">Save</button></td>


How can I do this?

Answer

You can use find() along with :first (or :eq(0)) to get the first td within the row. You can also change the text and class of the clicked button using text() and addClass() respectively. Finally you can place the content in an input by appending it to the td. Try this:

$('.editBtn').click(function() {
  var $button = $(this).addClass('save').text('Save');
  var $tr = $button.closest('tr');
  var id = $tr.data('id');
  var $td = $tr.find('td:first');
  
  $td.html('<input value="' + $td.text() + '" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr data-id="2">
    <td>Foo</td>
    <td>
      <button class="editBtn">Edit</button>
    </td>
  </tr>
  <tr data-id="3">
    <td>Bar</td>
    <td>
      <button class="editBtn">Edit</button>
    </td>
  </tr>
</table>