Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda