Skip to content Skip to sidebar Skip to footer

Targetting A From It's Parents 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 element bad practice? I've got the follow

Solution 1:

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>

Post a Comment for "Targetting A From It's Parents With Data-attributes Using Jquery"