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.
You can use
.prev()to select the span previous tobutton, and the id's should always be unique, so I changed the idfieldtofield_1,field_2,field_3, and I've replaced theupdate.contentEditable = true;withupdate[0].contentEditable = true;: