How do I retrieve the td's in a tr where the td index (within the row) is not 1 or 2? That is, I want to skip the first two columns. The following code gets the job done but is there a better way to do it? I’m thinking (td eq(0) || eq(1)) something like that.
$("#time-entry tr").each(function () {
var trId = $(this).attr('id');
$(String.format("#{0} td input[id^=txt]", trId)).each(function () { //rewrite
var tdIndex = $(this).index();
if(tdIndex != 1 && tdIndex != 2) {
}
});
});
I’d like to suggest an alternative approach, completely ignoring how to do things by index (which you can already see how to do from the other answers) and instead try to solve the underlying problem in a simple and maintainable way.
You said in a comment that what are really trying to do is add up some textboxes and put the row total in the last column, so to me it makes sense to select them directly rather than selecting the containing
tdelements. You did note that the first two columns have textboxes that you don’t want to select but we can easily allow for that.Rather than messing around with column indexes, which means you’ll have to change your code if you later insert/delete/re-order columns, I suggest you give a common class to the elements you want to add up and then another class to the (last column) row-total elements. So something like this in your markup:
(Obviously you’ll have other attributes but that was just a sample to show the classes.)
Then the JS is really simple:
If you insert extra columns in the middle that shouldn’t be added, no problem: without the “addup” class they’ll be ignored automatically.
Note also that your code:
$(String.format("#{0} td input[id^=txt]", trId))seems to be trying to use a C# method in the middle of your JavaScript, which won’t work. But you don’t need to worry about trying to select elements based on the current row’s id because within the$("tr").each()handler the keywordthiswill refer to the current row so you can pass that to the$()function as context for the selection. So like$(".addup", this)as shown above.