Search code examples
jqueryhtml-tabletraversaltablerow

Jquery navigate to parent <tr>. Issues with using parent() or closest() selectors


I am not able to achieve something that seems so simple. Not sure where I am going wrong. Please advise. Goal is to highlight a table row is the checkbox corresponding to it is selected. I have referred to several examples that talks about using .closest('tr') or .parent('tr') to get this working but for some reasons in my case - its over achieving i.e. it highlights all the rows rather than just the one that is selected.

My HTML

<tr class="EvenRowClass">
 <td class="ColClass">
   <div class="wrapClass" ">
 <span class="tableCol" style="background: someimage.png") </span>
 <span class="tableCol" style="background: someimage.png") </span>
 <input id="Check1" class="selectCheck" type="checkbox"
      onclick="highlightRow(this,Check1); return false;" value="Check1">
</div>
 </td>
 <td>SomeCode</td>
 <td>SomeCode</td>
 <td>SomeCode</td>

Assume that there is another block of such code with a and unique ids for each check box sequential)

My JavaScript function that gets called on click

    function highlightRow(checkbox, id)
{
   $("tr:parent").toggleClass("highlight", checkbox.checked);   
}   

The javascript above selects all the in the table and rest of the page regardless of whether they are checkd or not and applies the highlight class to it. I tried several other version using checkbox selector , .closest('tr'), .parent('tr') but none of them have worked for me.

The last few mentioned are only better in the sense they affect the only within the table and not others on the page.

Please advise. I have scratched my head over this enough that it started hurting now.


Solution

  • function highlightRow( checkbox, id ) {
        $( checkbox ).closest( 'tr' ).toggleClass( 'highlight', checkbox.checked );  
    };