How to Set Focus on the Next Form Input With JavaScript

Last updated on March 03, 2023
How to Set Focus on the Next Form Input With JavaScript

To move focus from one input to the next one in a form:

  1. Get a list of all the input elements in the form.
  2. Get the index of the input element in the list that has focus.
  3. Get the index of the next input element in the list.
  4. Focus on it.
function focusNext() {
  const currInput = document.activeElement;
  const currInputIndex = inputs.indexOf(currInput);
  const nextinputIndex =
    (currInputIndex + 1) % inputs.length;
  const input = inputs[nextinputIndex];
  input.focus();
}

For example:

<form class="form">
  <input
    type="number"
    name="num1"
    id="num1"
    placeholder="1st Number"
    maxlength="2"
  />
  <input
    type="number"
    name="num2"
    id="num2"
    placeholder="2nd Number"
    maxlength="3"
  />
  <input
    type="number"
    name="num3"
    placeholder="3rd Number"
    id="num3"
    maxlength="4"
  />
  <button type="submit" id="submit-btn">Submit</button>
</form>
.form {
  display: flex;
  flex-direction: column;
  width: 200px;
}

.form input:not(:first-of-type) {
  margin-top: 10px;
}

.form #submit-btn {
  margin-top: 20px;
}
// Convert NodeList to Array with slice()
const inputs = Array.prototype.slice.call(
  document.querySelectorAll('.form input')
);

inputs.forEach((input) => {
  input.addEventListener('keydown', (event) => {
    const num = Number(event.key);
    if (num && num >= 0 && num <= 9) { // Only allow numbers
      if (input.value.length >= input.maxLength) {
        event.preventDefault();
        focusNext();
      }
    }
  });
});

function focusNext() {
  const currInput = document.activeElement;
  const currInputIndex = inputs.indexOf(currInput);
  const nextinputIndex =
    (currInputIndex + 1) % inputs.length;
  const input = inputs[nextinputIndex];
  input.focus();
}
The next input gains focus when the input limit is reached.
The next input gains focus when the input limit is reached.

We use the document.querySelectorAll() method to obtain a collection of all the input elements in the form. This method in JavaScript allows you to find all the elements on a web page that match a certain pattern or characteristic, such as all elements with a particular class name or tag name.

We use the forEach() method to iterate over the array of input elements we obtained using document.querySelectorAll(). For each input element, we add an event listener to listen for the keydown event.

When a key is pressed down, we check if the key pressed is a number between 0 and 9. If it is, we check if the length of the input's value is equal to its maxLength attribute. If it is, we prevent the default action of the event and call the focusNext() function to move the focus to the next input element.

The forEach() method is a higher-order function in JavaScript that allows you to run a function on each element of an array.

Tip: A higher-order function is a function that can take in functions as arguments and/or return a function.

In the focusNext() function, we first get the currently focused input element using document.activeElement. We then get the index of this input element in the inputs array we created earlier using inputs.indexOf(currInput).

We then calculate the index of the next input element in the array using (currInputIndex + 1) % inputs.length, where % is the modulo operator. This ensures that if the currently focused input element is the last one in the array, we wrap around to the first input element.

Finally, we get a reference to the next input element using inputs[nextinputIndex] and call the focus() method on it to move the focus to the next input element.

Set focus on next input on enter

Sometimes, we want to move the focus to the next input element when the user presses the Enter key instead of waiting for the input's maxLength to be reached. To do this, we can add an event listener to listen for the keydown event on each input element. When the Enter key is pressed, we prevent the default action of the event and call the focusNext() function to move the focus to the next input element.

inputs.forEach((input) => {
  input.addEventListener('keydown', (event) => {
    if (event.key === 'Enter') {
      event.preventDefault();
      focusNext();
    }
  });
});

Now, when the user presses the Enter key, the focus will move to the next input element. This can be especially useful in forms where the user needs to quickly move through a series of inputs without having to manually click on each one.

Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also