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 jQuery 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
Give the
tds of interest a classname so that you can select them using the classname selector.with
You would probably also rather use
text()to get its contents. Thehtml()would return any the containing HTML as well which might not be of your interest.Have you considered as well to use the
<input type="radio">to force a single selection? If you give them all the samename, then they belongs to the same single selection group.