mrtonyb
mrtonyb

Reputation: 615

jQuery to select next table row

I have two rows of a table here. When I click the checkbox in the first table row, I'm trying to target the ID of the span in the next table row. I have an alert in my code just to show me that I was successful.

What I have isn't working. I can't figure out a way to select data in the next table row when the checkbox in the first row is clicked.

<table>
<tr id="row-a">
<td>
    <input type="checkbox">
    <span>
        some text
    </span>
</td>
</tr>
<tr>
<td>
    <span id="target">
        some text
    </span>
</td>
</tr>
</table>

$(document).ready(function() {
   var myCheck = $("tr#row-a td input");

   myCheck.change(function(){
   var spanID = $("tr#row-a').next('tr').find('span').attr('id');
   alert(spanID);
   });
});

Upvotes: 3

Views: 16291

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337713

Try this:

var myCheck = $("tr#row-a td input");
myCheck.change(function(){
    var spanID = $(this).closest('tr').next().find('span').attr('id');
    alert(spanID);
});

Example fiddle

Upvotes: 6

Adriano Carneiro
Adriano Carneiro

Reputation: 58645

$(document).ready(function() {
   var myCheck = $("tr#row-a td input");

   myCheck.change(function(){
   var spanID = myCheck.parents("tr").next().find('span').attr('id');
   alert(spanID);
   });
});

The change was in this line:

   var spanID = myCheck.parents("tr").next().find('span').attr('id');

Which does the following:

  • Finds the checkbox's tr parent
  • Gets the next sibling node (next tr)
  • Finds the span
  • Gets its id

Upvotes: 3

Related Questions