Select a specific closest item

I have the following html:

<table id="objects"> <tr> <td> <input type="text" value="2" /> </td> <td> <a href="#" class="delete">link</a> </td> </tr> <tr> <td> <input type="text" value="4" /> </td> <td> <a href="#" class="delete">link</a> </td> </tr> </table> 

When I click on the anchor tag, I would like to select the <input> closest to my link and get its value. How can i do this? I have tried:

  $('.delete').click(function(e){ e.preventDefault(); var val = $(this).closest('input').attr('value'); alert(val); }); 

but no luck.

+4
source share
4 answers

The name of the closest function is extremely misleading: it is actually the closest ancestor that returns.

The correct code is:

 var value = $(this).parent().siblings('td').children('input').val(); 

I would not recommend attaching an event handler to alllllllll anchor tags; this will be ineffective if there are several elements on the page. Instead, I would highly recommend use delegate () or live () instead.

 $('#objects').delegate('a.delete', 'click', function (e) { e.preventDefault(); var val = $(this).parent('td').siblings('td').find('input').attr('value'); alert(val); }); 

This will attach the event handler to the table (once), and then use the JavaScripts bubbling mechanisms to detect clicks on the elements that match the selector passed in the first argument (in this case, your delete buttons).

+3
source

If you look at the documentation for the nearest , you will see that he says that he finds his ancestors ..

Description Get the first ancestor . an element that matches the selector, starting from the current element and moving up through the DOM tree.

the entry in your case is not the ancestor of the .delete link.

You need to go up with .closest('tr') and then turn around to find the input with .find('input')

So

 var val = $(this).closest('tr').find('input').val(); 
+3
source

Try

 $('.delete').click(function (e) { e.preventDefault(); var val = $(this).parent("td").prev().find('input').val(); alert(val); }); 
0
source

See Working Demo


You cannot use closest there, try the following:

  $('.delete').click(function(e){ e.preventDefault(); var val = $(this).parent('td').prev('td').find('input').attr('value'); alert(val); }); 

parent() used to return to the parent td link, and then prev() used to search for the previous td brother, and finally, using the find method, the input search is performed.

Additional Information:

0
source

All Articles