Categories
JavaScript Answers

How to advance to the next form input when the current input has a value with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *