To advance to the next form input when the current input has a value with JavaScript, we find the next input and call focus
on it.
For instance, we write
window.onkeypress = (e) => {
if (e.which === 13) {
e.preventDefault();
const nextInput = inputs.get(inputs.index(document.activeElement) + 1);
nextInput?.focus();
}
};
to set the window.onkeypress
property to a function that checks if enter is pressed with e.which === 13
.
If it is, then we call preventDefault
to stop the default behavior.
Then we use inputs.get
to get the next input.
And then we call focus
on it to make it focused.
Conclusion
To advance to the next form input when the current input has a value with JavaScript, we find the next input and call focus
on it.