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();
}
}
});
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();
}
}
});
Share
Improve this question
edited Sep 1, 2014 at 13:21
Adrian Forsius
1,4382 gold badges19 silver badges29 bronze badges
asked Jan 28, 2012 at 0:30
Asim ZaidiAsim Zaidi
28.3k49 gold badges137 silver badges224 bronze badges
2
|
4 Answers
Reset to default 14If 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
});
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(',');
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
}
});
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);
something
is an object, instead of an array? – David Torres Commented Mar 24, 2016 at 17:57