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

157
Views
How to add a conditional to the last element of a loop

I understand the problem I have facing, but I don't know how to go about fixing it. I have 6 input fields whereby, whenever you enter a value in one input field, it goes to the next and then activates the .focus() method.

The issue here is that, after the last input field, there is no more input field which then leads to the error, "Cannot read properties of undefined (reading 'focus')".

I have tried adding several else if's statement to disable the focus after the last input field has been entered but seems its not working and I keep getting the error.

index.html

<div class="code-container">
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
</div>

script.js

const codes = document.querySelectorAll(".code");

codes[0].focus();

codes.forEach((code, idx) => {
  code.addEventListener("keydown", (e) => {
    console.log(idx);
    if (e.key >= 0 && e.key <= 9) {
      codes[idx].value = "";
      setTimeout(() => codes[idx + 1].focus(), 10);
    } else if (e.key === "Backspace") {
      setTimeout(() => codes[idx - 1].focus(), 10);
    } else if (idx == codes.length - 1) {
      codes[idx].blur();
    }
  });
});

error log

script.js:10 Uncaught TypeError: Cannot read properties of undefined (reading 'focus')
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

That is probably a job for the modulo operator.

Replace idx + 1 by (idx + 1) % codes.length.

Here is your code changed a little...
To take in account the blur expected for the last input... And to avoid an error on backspace on the first one.

const codes = document.querySelectorAll(".code");

codes[0].focus();

codes.forEach((code, idx) => {
  code.addEventListener("keydown", (e) => {
    console.log(idx);
    
    if (e.key >= 0 && e.key <= 9) {
      if (idx == codes.length - 1) {
       setTimeout(() => codes[idx].blur(), 10);
        return
      }
      codes[idx].value = "";
      setTimeout(() => codes[(idx + 1) % codes.length].focus(), 10);
    } else if (e.key === "Backspace" && idx != 0) {
      setTimeout(() => codes[(idx - 1) % codes.length].focus(), 10);
    }
  });
});
<div class="code-container">
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
  <input type="number" class="code" placeholder="0" min="0" max="9" required>
</div>

about 4 years ago · Juan Pablo Isaza Report

0

you definitely should compare the codes.length and compare it with idx to apply the move to the next element except the last one as below

    const codes = document.querySelectorAll(".code");
    codes[0].focus();
    const codexLastIndex = codes.length - 1;

    codes.forEach((code, idx) => {
      code.addEventListener("keydown", (e) => {
        console.log(idx);
        const isLastElement = e.target == codes[codes.length - 1];
        const isFirstElement = e.target == codes[0];

        // special use case for the last element 
        if (isLastElement) {
         if ( e.key >= 0 && e.key <= 9) {
          codes[idx].value = e.key;
         } 
        }
        if ( ( e.key >= 0 && e.key <= 9) && !isLastElement) {
          codes[idx].value = "";
          setTimeout(() => codes[idx + 1].focus(), 10);

        } else if (e.key === "Backspace" && !isFirstElement) { // remove the error with the backspace in the first element
          setTimeout(() => codes[idx - 1].focus(), 10);
        } else if (idx == codes.length - 1) {
          codes[idx].blur();
        }
      });
    });

this code uses e.preventDefault(); for logic wise https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

 const codes = document.querySelectorAll(".code");
    codes[0].focus();
    const codexLastIndex = codes.length - 1;

    codes.forEach((code, idx) => {

      code.addEventListener("keydown", (e) => {
        e.preventDefault(); // here adding preventDefault() function to stop the defaults actions 
        const isLastElement = e.target == codes[codes.length - 1];
        const isFirstElement = e.target == codes[0];

        // special use case for the last element 
        if (isLastElement) {
         if ( e.key >= 0 && e.key <= 9) {
          codes[idx].value = e.key;
         } 
        }
        if ( ( e.key >= 0 && e.key <= 9) && !isLastElement) {
          codes[idx].value = e.key;
          setTimeout(()=> codes[idx + 1].focus(), 10);

        } else if (e.key === "Backspace" && !isFirstElement) { // remove the error with the backspace in the first element
          setTimeout(() => codes[idx - 1].focus(), 10);
        } else if (idx == codes.length - 1) {
          codes[idx].blur();
        }
      });
    });
about 4 years ago · Juan Pablo Isaza Report

0

You can try to change codes[idx].blur(); to e.preventDefault You can also see here for more details enter link description here

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!