skip to Main Content

i am trying to create an input field with 6 inputs:

function focusNext(currentInput, nextIndex) {
  if (currentInput.value.length === 1) {
    const nextInput = document.querySelector(`input:nth-child(${nextIndex})`);
    if (nextInput) {
      nextInput.focus();
    }
  }
}
<div class="code-input">
  <input type="text" @bind=code0 maxlength="1" onkeyup="focusNext(this, 1)">
  <input type="text" @bind=code1 maxlength="1" onkeyup="focusNext(this, 2)">
  <input type="text" @bind=code2 maxlength="1" onkeyup="focusNext(this, 3)">
  <input type="text" @bind=code3 maxlength="1" onkeyup="focusNext(this, 4)">
  <input type="text" @bind=code4 maxlength="1" onkeyup="focusNext(this, 5)">
  <input type="text" @bind=code5 maxlength="1">
</div>

I want it to automatically jump to the next input field, once the previous one is filled out.

But just nothing happens.
As this is inside a blazor context, I cannot use jquery.

Can someone spot my error?

Thanks!

2

Answers


  1. nth-child indexes start at 1 not 0

    function focusNext(currentInput, nextIndex) {
      if (currentInput.value.length === 1) {
        const nextInput = document.querySelector(`input:nth-child(${nextIndex + 1})`);
        if (nextInput) {
          nextInput.focus();
        }
      }
    }
    <div class="code-input">
      <input type="text" @bind=code0 maxlength="1" onkeyup="focusNext(this, 1)">
      <input type="text" @bind=code1 maxlength="1" onkeyup="focusNext(this, 2)">
      <input type="text" @bind=code2 maxlength="1" onkeyup="focusNext(this, 3)">
      <input type="text" @bind=code3 maxlength="1" onkeyup="focusNext(this, 4)">
      <input type="text" @bind=code4 maxlength="1" onkeyup="focusNext(this, 5)">
      <input type="text" @bind=code5 maxlength="1">
    </div>
    Login or Signup to reply.
  2. Rather than using querySelector, consider using querySelectorAll. This will provide you with a NodeList, from which you can then select the specific element you wish to focus on.

    function focusNext(currentInput, nextIndex) {
      if (currentInput.value.length === 1) {
        const nodes = document.querySelectorAll(`.code-input input`);
        if (nextIndex < nodes.length)
          nodes[nextIndex].focus();
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search