Search code examples
javascriptjquerycontenteditable

Make contenteditable for a specific table span using JS onclick


I have a simple table where I'm trying to allow for the field value to be made contenteditable after pressing the edit button that I am printing next to each value:

 <table>  
 <tr>  
 <th>Variable A</th>  
 <th>Variable B</th>  
 <th>Variable C</th>  
 <tr>  
 <td><span id="field">Value A</span> <button type="button" class="result">EDIT</button></td>  
 <td><span id="field">Value B</span> <button type="button" class="result">EDIT</button></td>  
 <td><span id="field">Value C</span> <button type="button" class="result">EDIT</button></td>   </tr> 
 </table>

I use the following jQuery upon clicking the Edit button

 $( document ).ready(function() {
        $("body").on('click', '.result', function() {
         var update = $(this).closest('td');
         document.getElementById('field').contentEditable = true;
         update.append('<button class=\"result\">Save</button></td>');
         $(this).remove();
    });
  });

Unfortunately when I click "Edit" button, only the first field (Value A) becomes editable.. I think this is because

 document.getElementById('field').contentEditable = true;

Is only updating the first instance of the id='field'

But I'm trying to make it only update the field next to where I pressed the button. So if I click the 3rd Edit button, it should make the Value C field be editable. Instead it only does Value A.

I realize that I need to make it specific to that span.. But not finding a solution. I tried:

$(this).closest('.field').contentEditable = true;

But if I do this then no spans become editable. I know this might be an easy question but I've tried all sorts of options to no avail.


Solution

  • You can use .prev() to select the span previous to button, and the id's should always be unique, so I changed the id field to field_1, field_2, field_3, and I've replaced the update.contentEditable = true; with update[0].contentEditable = true;:

    $("body").on('click', '.result', function() {
       var update = $(this).prev('span');
       var td = $(this).closest('td');
       update[0].contentEditable = true;
       td.append('<button class=\"result\">Save</button></td>');
       $(this).remove();
     });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <tr>
        <th>Variable A</th>
        <th>Variable B</th>
        <th>Variable C</th>
        <tr>
          <td><span id="field_1">Value A</span> 
            <button type="button" class="result">EDIT</button>
          </td>
          <td><span id="field_2">Value B</span> 
            <button type="button" class="result">EDIT</button>
          </td>
          <td><span id="field_3">Value C</span> 
            <button type="button" class="result">EDIT</button>
          </td>
        </tr>
    </table>