Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
Move to previous input on keydown using javascript

I want to move to the next inputbox with javascript whenevever the maxlength of an inputbox is reached. When the backspace key is pressed I want to clear the current inputbox and move to the previous one.

This is kind of working. Except whenever I press the backspace key it goes to the previous inputbox but doesn't clear the one I was currently on.

Example;

var elts = document.getElementsByClassName('test')
Array.from(elts).forEach(function(elt){
  elt.addEventListener("keydown", function(event) {
    // Number 13 is the "Enter" key on the keyboard
    if (event.keyCode === 13 || elt.value.length == 1) {
      // Focus on the next sibling
      elt.nextElementSibling.focus()
    }
    if( event.keyCode == 8)
      {
        if (elt.previousElementSibling != null)
        {
            elt.previousElementSibling.focus();
        }
      }
  });
})
body {
    margin: 1em;
}

.field {
    margin-bottom: 1em;
}
<input type="text" class="test" id="0" maxlength="1"/>
<input type="text" class="test" id="1" maxlength="1"/>
<input type="text" class="test" id="2" maxlength="1"/>
<input type="text" class="test" id="3" maxlength="1"/>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try

var elts = document.getElementsByClassName('test')
Array.from(elts).forEach(function(elt) {
  elt.addEventListener("keydown", function(event) {
    // Number 13 is the "Enter" key on the keyboard
    if (event.keyCode === 13 ||
        event.keyCode !== 8 && elt.value.length === Number(elt.maxLength)
    ) {
      // Focus on the next sibling
      elt.nextElementSibling.focus()
    }
    if (event.keyCode == 8) {
      elt.value = '';
      if (elt.previousElementSibling != null) {
        elt.previousElementSibling.focus();
        event.preventDefault();
      }
    }
  });
})
body {
  margin: 1em;
}

.field {
  margin-bottom: 1em;
}
<input type="text" class="test" id="0" maxlength="1" />
<input type="text" class="test" id="1" maxlength="1" />
<input type="text" class="test" id="2" maxlength="1" />
<input type="text" class="test" id="3" maxlength="1" />

about 4 years ago · Juan Pablo Isaza Relatório

0

using key instead of keyCode

key is what the user intends to see (holds shift or capslock for "A", or not for "a")

and take advantage of the method getAttribute

getAttribute method of the Element interface returns the value of a specified attribute on the element.

also I've used Destructuring and Optional chaining to avoid error if a previous element doesn't exist nullish (null or undefined)

var inputs = document.getElementsByClassName("test");
Array.from(inputs).forEach(function (input) {
  input.addEventListener("keydown", keyhandler);
});
function keyhandler(e) {
  let { key } = e;
  let max = this.getAttribute("maxlength");
  if (key == "Backspace") {
    this.value = "";
    this?.previousElementSibling?.focus();
    e.preventDefault();
  } else if (key == "Enter" || this.value.length >= max) {
    this.nextElementSibling.focus();
  }
}
body {
  margin: 1em;
}
.field {
  margin-bottom: 1em;
}
<input type="text" class="test" id="0" maxlength="1" />
<input type="text" class="test" id="1" maxlength="1" />
<input type="text" class="test" id="2" maxlength="1" />
<input type="text" class="test" id="3" maxlength="1" />

about 4 years ago · Juan Pablo Isaza Relatório

0

Have you tried to make the value of the input equal to an empty string? Like that: elt.setAttribute(value, '')

Source:

input element, look up for attributes

js method for attributes

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda