3

I am trying to get the closest table when I search for a value.

This is my code but I always get 'undefined'.

jQuery :

 $(function() {
     $("#searchValue").keyup(function() {
         alert($(this).closest('table').attr('id'));
     });
 });

HTML:

<input type='text' name='searchValue' id='searchValue'/>

<table id='tablePlanning' class='tablesorter'>
    <thead>
        <tr>
            <th>PR Code</th>
            <th>Klant</th>
            <th>Description</th>
            <th>Project status</th>
            <th>Project Leader</th>
            <th>Coordinator</th>
            <th>Account manager</th>
            <th>Billing</th>
            <th>Start Datum</th>
            <th>Hardware</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>
New Alexandria
  • 6,951
  • 4
  • 57
  • 77
David
  • 840
  • 6
  • 17
  • 37

1 Answers1

4

Try to use .next() to find the following table (at the same DOM level) instead :

$(function() {
   $("#searchValue").keyup(function() {
     alert($(this).next('table').attr('id'));
   });
});

.closest() is to find the first parent of the element.

But since your table has an id, you should use it (I hope you don't have several tables with the id #tablePlanning otherwise, you should use a classname.

Brewal
  • 8,067
  • 2
  • 24
  • 37
  • 2
    To be specific, `closest()` matches the first element in the ancestor chain that matches the selector, *including the source element itself*. – Frédéric Hamidi Dec 09 '13 at 16:21