Navigate focus by setting tabindexes

Hm I’d rather not go with those solutions TBH… they’re all suggesting to listen to key events, which would also prevent you from using tab, shift and arrow keys once the max length is reached… not to mention they’re hard-coding the max lengths in the JS, rather than setting the actual maxlength attribute. Using jQuery, of course.

So here’s a simple generic solution, that also should not conflict with keyboard navigation:

<input type="text" maxlength="3" class="auto-focus-next">
<input type="text" maxlength="5" class="auto-focus-next">
<input type="text" maxlength="2" class="auto-focus-next">
function initAutoFocus (input, index, list) {
  const next = list[index + 1]

  if (!next) {
    return
  }

  input.addEventListener('input', () => {
    if (input.value.length === input.maxLength) {
      next.focus()
    }
  })
}

document
  .querySelectorAll('.auto-focus-next')
  .forEach(initAutoFocus)
3 Likes