I am trying to work out how to get the value of table cell for each row using jQuery.
My table looks like this:
<table id="mytable">
<tr>
<th>Customer Id</th>
<th>Result</th>
</tr>
<tr>
<td>123</td>
<td></td>
</tr>
<tr>
<td>456</td>
<td></td>
</tr>
<tr>
<td>789</td>
<td></td>
</tr>
</table>
I basically want to loop through the table, and get the value of the Customer Id
column for each row.
In the code below I have worked out that I need to do this to get it looping through each row, but I'm not sure how to get the value of the first cell in the row.
$('#mytable tr').each(function() {
var cutomerId =
}
a less-jquerish approach:
this can obviously be changed to work with not-the-first cells.
What you are doing is iterating through all the trs in the table, finding the first td in the current tr in the loop, and extracting its inner html.
To select a particular cell, you can reference them with an index:
In the above code, I will be retrieving the value of the third row (the index is zero-based, so the first cell index would be 0)
Here's how you can do it without jQuery:
Try this,
If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:
Essentially this is the same as the other solutions (possibly because I copypasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a < span >, provided you keep the class attribute with it.
By the way, I think you could do it in one selector:
If that makes things easier