2

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?

Community
  • 1
  • 1
Andy
  • 5,142
  • 11
  • 58
  • 131

1 Answers1

6

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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Good job KFC king. – Offir Nov 08 '16 at 16:11
  • and if the html can change one day it's better to give a class to the td with the name lets say the class is name then access it $tr.find('.name') – Ryad Boubaker Nov 08 '16 at 16:11
  • I think he need's HTML5 contenteditable attribute of tables. –  Nov 08 '16 at 16:16
  • @user2521387 feel free to add your own answer. I wouldn't call this wrong at all. If you want to use `contenteditable` I wish you the best of luck getting it working reliably in IE on a `td` element, and also re-inventing the wheel when serialising the `form` contents before sending, as when using this method you can just call the `serialize()` method. – Rory McCrossan Nov 08 '16 at 16:19
  • 2
    Keep the comments civil and constructive please people. – Jon Clements Nov 08 '16 at 16:36