Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving to next input automatically

I have many <input>s which accept at most three characters, as shown.

<input type="text" id="0" maxlength="3"/>
<input type="text" id="1" maxlength="3"/>
<input type="text" id="2" maxlength="3"/>
<input type="text" id="3" maxlength="3"/>

Can we:

  • allow the user to move textboxes by pressing the Enter key?
  • automatically move the user to the next text box after entering three or more characters?

I have seen a few questions on this topic using JQuery, but I am looking for an exclusively JavaScript solution, if at all possible.

like image 980
flame Avatar asked Jul 16 '26 03:07

flame


1 Answers

You can iterate through elements of the same class name and detect two different events.

var elts = document.getElementsByClassName('test')
Array.from(elts).forEach(function(elt){
  elt.addEventListener("keyup", function(event) {
    // Number 13 is the "Enter" key on the keyboard
    if (event.keyCode === 13 || elt.value.length == 3) {
      // Focus on the next sibling
      elt.nextElementSibling.focus()
    }
  });
})
<input type="text" class="test" id="0" maxlength="3"/>
<input type="text" class="test" id="1" maxlength="3"/>
<input type="text" class="test" id="2" maxlength="3"/>
<input type="text" class="test" id="3" maxlength="3"/>
like image 73
djcaesar9114 Avatar answered Jul 18 '26 16:07

djcaesar9114



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!