Reputation: 28284
I have the following code that I am going through the tables columns and if its the last column I want it to do something different. Right now its hard coded but how can I change so it automatically knows its the last column
$(this).find('td').each(function (i) {
if(i > 0) //this one is fine..first column
{
if(i < 4) // hard coded..I want this to change
{
storageVAR += $(this).find('.'+classTD).val()+',';
}
else
{
storageVAR += $(this).find('.'+classTD).val();
}
}
});
Upvotes: 10
Views: 14402
Reputation: 348
Something like this should do it:
var $this = $(this),
size = $this.length,
last_index = size -1;
$this.find('td').each(function (index) {
if(index == 0) {
// FIRST
} else if(index === last_index) {
// LAST
} else {
// ALL THE OTHERS
}
});
Upvotes: 2
Reputation: 161457
It looks like your objective is to make a comma separated list of the values, why don't you collect the values and use the array method 'join'?
var values = []
$(this).find('td .' + classTD).each(function(i) {
if (i > 0) values.push($(this).val());
});
storageVAR = values.join(',');
Upvotes: 6
Reputation: 16953
If all you want is the last column, you can use
$(this).find('td:last')
If you want to do things with other columns, go for
$(this).find('td:last').addClass("last");
$(this).find('td').each(function() {
if ($(this).hasClass("last")) {
// this is the last column
} else {
// this isn't the last column
}
});
You can use data()
instead of addclass()
if you're comfortable with that.
If all you want to do is not have a comma at the end of your string, you could just chop it off afterward:
storageVAR = storageVAR.substr(0, (storageVAR.length - 1);
Upvotes: -2
Reputation: 707238
If you want access to the length inside the .each()
callback, then you just need to get the length beforehand so it's available in your scope.
var cells = $(this).find('td');
var length = cells.length;
cells.each(function(i) {
// you can refer to length now
});
Upvotes: 14