Reputation: 142
Am trying to print < tr > row number in a table of 20 rows.
I'm not so well-versed in jQuery syntax, but this is basically what I need
var rowIndex = 1;
// for each row increase rowIndex + 1
$('.tablerow').html(rowIndex)
Much thnx for any help you can throw my way.
Upvotes: 0
Views: 5504
Reputation: 33865
You could use .each()
to loop over the rows. If .tablerow
is a class on the tr-element, you could loop over each row like this:
$('.tablerow').each(function (i) {
$("td:first", this).html(i);
});
The example will add the index to the first td-element on each row.
If you don't want to add the index to the first td-element, your can use the .eq()
method to select any td you want by specifying its index within the tr-element (zero-based).
$('.tablerow').each(function (i) {
$("td", this).eq(2).html(i);
});
Above example will write the index to the third td-element on each row.
Start at one:
To start at 1 instead of 0, all you have to do is to add one to the index when printing it
$('.tablerow').each(function (i) {
$("td:first", this).html(i + 1);
});
Upvotes: 5
Reputation: 707238
You can use .each()
to run a custom function on each item in a collection. You don't show us your exact HTML so we don't know exactly which item .tablerow
is. Here are two options depending upon what .tablerow
is:
Assuming .tablerow
is your tr
:
$(".tablerow td:first").each(function(index) {
$(this).html(index);
});
If .tablerow
is already the first td
in each row, then it can just be this:
$(".tablerow").each(function(index) {
$(this).html(index);
});
Upvotes: 0