Pressing the Backspace key, delete the previous input fields

Asked

Viewed 466 times

1

The code below causes the user to type in a given input field, it jumps to the other field automatically:

<form class="form-inline">
 <div align="center">    
  <div class="form-group">
      <input type="password" class="form-control" style="width: 70px" maxlength="1" id="campo1" value="" onkeyup="if(this.value.length >= 1) { campo2.focus(); }">
  </div>
  <div class="form-group">
      <input type="password" class="form-control" style="width: 70px" maxlength="1" id="campo2" value="" onkeyup="if(this.value.length >= 1) { campo3.focus(); }">
  </div>
   <div class="form-group">
      <input type="password" class="form-control" style="width: 70px" maxlength="1" id="campo3" value="" onkeyup="if(this.value.length >= 1) { campo4.focus(); }">
  </div>
  <button type="submit" id="campo7" class="btn btn-default">Acessar</button>
 </div> 
</form>

So far so good, but as I would do in case the user wanted to delete the previous fields by pressing the Backspace key?

Thank you

1 answer

1


I find it simpler to do all the logic directly in javascript, building all the functions of onkeyup simultaneously through a for.

//apanhar todos os inputs
let inputs = document.querySelectorAll(".form-inline input");

//ou especificando cada um individualmente
//let inputs = [
//  document.getElementById("campo1"), 
//  document.getElementById("campo2"), 
//  document.getElementById("campo3") ];

for (let i = 0; i < inputs.length; ++i){
  inputs[i].onkeyup=function(evento){ //construir o onkey para cada um

    if (evento.key == "Backspace"){ //se for backspace estamos a apagar
      if (i > 0 && this.value.length == 0){ //se não for o 1º e se tiver vazio
        inputs[i-1].focus();
      }
    }
    else if ((i+1) < inputs.length && this.value.length >= 1){ //se não for o ultimo e tiver 1 caracter
      inputs[i+1].focus();
    }
  }
}
<form class="form-inline">
 <div align="center">    
  <div class="form-group">
      <input type="password" class="form-control" style="width: 70px" maxlength="1" id="campo1" value="">
  </div>
  <div class="form-group">
      <input type="password" class="form-control" style="width: 70px" maxlength="1" id="campo2" value="">
  </div>
   <div class="form-group">
      <input type="password" class="form-control" style="width: 70px" maxlength="1" id="campo3" value="">
  </div>
  <button type="submit" id="campo7" class="btn btn-default">Acessar</button>
 </div> 
</form>

  • Perfect Isac. It worked!! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.