Link to home
Start Free TrialLog in
Avatar of areyouready344
areyouready344Flag for United States of America

asked on

how to keep track of a previous loop count using jquery?

how to keep track of a previous loop count using jquery?

for example,

$("#list li").filter:gt('+ variable+').each(function(
{
       if(start > finish)
       {
            loopCount = loopCount + 1;
            $('#list2 li').append('<li>' + variable + '</li>');
       }

}))

Now if I go through this each loop again, I need to know what was the previous loop count.
Avatar of leakim971
leakim971
Flag of Guadeloupe image

put the variable outside the each or as global variable :

var loopCount = 0;
$("#list li").filter:gt('+ variable+').each(function(
{
       if(start > finish)
       {
            loopCount = loopCount + 1;
            $('#list2 li').append('<li>' + variable + '</li>');
       }

}))

Open in new window


or :


var loopCount = 0;
var loopCount = 0;
$(document).ready(function() {

$("#list li").filter:gt('+ variable+').each(function(
{
       if(start > finish)
       {
            loopCount = loopCount + 1;
            $('#list2 li').append('<li>' + variable + '</li>');
       }

}))

})

Open in new window

Avatar of areyouready344

ASKER

but how do I get the previous loop count in a current loop?
it's loopCount value
Let say for example, I have the following code

$("#click").click(function(
{
      var loopCount = 0;

       $("#list li").filter:gt('+ variable+').each(function(
       {
             if(start > finish)
            {
                  loopCount = loopCount + 1;
                 $('#list2 li').append('<li>' + variable + '</li>');
             }
          });
});

During each click of button, I want the loopCount to start at zero and count up. Upon additional clicks, I need to know what was the previous loopCount.
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks leakim but I wondering how to get lastLoopCountValue to read null during the first iteration of the loop.

var lastLoopCountValue = null;
$(document).ready(function() {

$("#click").click(function(
{
      var loopCount = 0;

       $("#list li").filter:gt('+ variable+').each(function(
       {
             if(start > finish)
            {
                  loopCount = loopCount + 1;
                 $('#list2 li').append('<li>' + variable + '</li>');
             }else
             {
                  alert(lastLoopCountValue); // its not reading a null value during the first iteration of the loop, which what I was expecting.
                  alert(loopCount);
             }
          });
       lastLoopCountValue = loopCount;
});
Put the alert before if(start > finish)