Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the last iteration in jquery each

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();
        }
    }
});
like image 760
Asim Zaidi Avatar asked Jan 28 '12 00:01

Asim Zaidi


People also ask

How do I get out of each loop in jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.

What is the use of each () function in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

What is each loop in jQuery?

The . each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.


1 Answers

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
});
like image 134
jfriend00 Avatar answered Oct 27 '22 01:10

jfriend00