wiredfordesign wiredfordesign - 4 months ago 15
Javascript Question

Selecting only one element with jQuery

I've got a table with a number of items. I'm trying to show input fields when a user clicks on an edit button, but I don't know how to select only the element within the same row as the edit button. Here's the table structure:

<table>

<tr class="table-row">
<td>
<a href="#" class="item-name">Item 1</a>
<input type="text" value="[item]" class="input-item" id="item-1">
</td>
<td>
<a href="#" class="item-name">Price 1</a>
<input type="text" value="[item]" class="input-item" id="price-1">
</td>
<td><a href="#" class="edit-button">Edit</a></td>
</tr>

<tr class="table-row">
<td>
<a href="#" class="item-name">Item 2</a>
<input type="text" value="[item]" class="input-item" id="item-2">
</td>
<td>
<a href="#" class="item-name">Price 2</a>
<input type="text" value="[item]" class="input-item" id="price-2">
</td>
<td><a href="#" class="edit-button">Edit</a></td>
</tr>

...

</table>


What I intend to happen, is that when the user clicks on the
Edit
link within a specific row, the input fields will appear (in the 1st and 2nd columns) and the text will disappear, allowing the user to edit from the table itself. Problem is, the jQuery code I have (obviously) selects all the
.input-item
classes, thus showing all the inputs from all the rows.

$('.edit-button').click(function(event){
$('.input-item').show();
});


How do I use jQuery to select only the inputs within the
.table-row
of the clicked
Edit
link?

Answer

You need traverse up to .table-row using .closest() method in current element context i.e. this, then use .find() to target descendant .input-item elements.

$('.edit-button').click(function(event){
  $(this).closest('.table-row').find('.input-item').show();
});