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
nth-child
indexes start at 1 not 0Rather 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.