Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
Reset counter in jQuery function

Ok, this seems pretty basic but I'm stuck.

I'm setting a var outside of the loop, then increment and once the counter reaches a threshold I need to reset it back to 0.

var cnt = 0;
$("ul").each(function(cnt) {
    var ths = $(this),
        tul = ths.attr("id");
        
    cnt = cnt++;
       
    if (cnt == 20) {
        cnt = 0;
    }
...
});

For some reason it keeps incrementing till the end of the look. What am I missing?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If cannot be reset to 0 because cnt is the .each(function(cnt) { function's index argument, and will always be the iterating index. You're trying to reset something to 0 which in the next loop will again be the index integer.

Depending on what's the desired (not clear from your question so far) you could simply not use the index attribute:

let cnt = 0;

$("ul").each(function() {
  cnt += 1;
       
  if (cnt === 20) {
    cnt = 0;
  }

   // ...
});

Modulo (reminder) operator

Use the reminder operator % to loop back to 0 once idx becomes 20.
In that case you don't need the outer variable, but you can use the iterating index attribute instead:

$("ul").each(function(idx) {
  const cnt = idx % 20;  // Reset to 0 once idx is 20  

   // ... 
});
about 4 years ago · Juan Pablo Isaza Report

0

The first argument to the function is the index of the array. Checkout the jQuery documentation. https://api.jquery.com/each/

You do not need to pass the parameter to the function. See code below.

var cnt = 0;
$("ul").each(function() {        
    cnt++;
   
    if (cnt == 20) {    
        cnt = 0;
    }
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!