magda
magda

Reputation: 43

Select specific closest element

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 anchor tag I'd like to select <input> closest to my link, and get it's value. How can I do this ? I was trying :

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

but without any luck.

Upvotes: 4

Views: 11870

Answers (4)

Sarfraz
Sarfraz

Reputation: 382909

See Working Demo


You can't use closest there, try this:

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

The parent() is used to go back to parent td of the link and then prev() is used to find the previous sibling of td and finally with find method, input is searched for.

More Info:

Upvotes: 0

Matt
Matt

Reputation: 75327

The name of the closest function is extremely misleading: it's actually the closest ancestor that is returned.

The correct code would be:

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

I wouldn't recommend binding the event handler to alllllllll anchor tags; this will be inefficient if there's a number of those elements on the page. Instead I would strongly recommend using 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 bind the event handler to the table (once), and then uses JavaScripts event bubbling mechanisms to detect the click on the elements which match the selector passed in the first argument (in this case your delete buttons).

Upvotes: 3

rahul
rahul

Reputation: 187110

Try

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

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196296

If you look at the documentation for closest you will see that it says that it finds ancestors ..

Description: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

the input in your case is not an ancestor of the .delete link.

You need to move up with .closest('tr') and then drill down to find the input with .find('input')

so

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

Upvotes: 4

Related Questions