Is there a better way to get values out of a table row?

Posted by chobo2 on Stack Overflow See other posts from Stack Overflow or by chobo2
Published on 2010-05-22T03:46:08Z Indexed on 2010/05/22 3:50 UTC
Read the original article Hit count: 195

Filed under:

Hi

Say I have this

<table border="1" id="tbl">
<tr>
<td><input type="checkbox" name="vehicle" value="Bike" /></td>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td><input type="checkbox" name="vehicle" value="Bike" /></td>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table> 

Now I want to get the row that is checked, then the cell values of that checked row. So I would do this

 var cells = $('#tbl :checked').parents('tr').children('td');

So lets assume only one checkbox can be checked(so no jqueyr foreach loop).

So now say I wanted to get the 2nd table cells value I would just go

var secondCell = $(cells[1]).html();

The thing with this though it makes the code so brittle. Like what if I put another table cell after after the checkbox one?

<table border="1" id="tbl">
<tr>
<td><input type="checkbox" name="vehicle" value="Bike" /></td>
   <td> I am new </td>
  <td>row 1, cell 1</td>
  <td>row 1, cell 2</td>
</tr>
<tr>
<td><input type="checkbox" name="vehicle" value="Bike" /></td>
   <td> I am new </td>
  <td>row 2, cell 1</td>
  <td>row 2, cell 2</td>
</tr>
</table> 

So now I have to go through my code and change this

var secondCell = $(cells[1]).html();

to this

var thirdCell = $(cells[2]).html();

since now I am actually after the 3rd cell and not the 2nd cell anymore.

So is there a better way?

Thanks

© Stack Overflow or respective owner

Related posts about jQuery