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:
I have seen a few questions on this topic using JQuery, but I am looking for an exclusively JavaScript solution, if at all possible.
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"/>