Just create a list of all input
s that exist in your form. For this, you can use:
const allFields = document.querySelectorAll('form input');
So I would do like this:
const allFields = document.querySelectorAll('form input');
allFields.forEach((field, index) =>
field.addEventListener('input', (event) => {
const maxLength = parseInt(event.target.getAttribute('maxlength'), 10);
const nextField = allFields[index + 1];
// Três condições farão com que o próximo campo NÃO seja focado:
// 1. O atributo `maxLength` não estiver definido (se isso ocorrer, a
// variável `maxLength` será `NaN`); Ou:
// 2. O valor do campo tiver um tamanho diferente do `maxLength`; Ou:
// 3. Não existir um próximo elemento.
if (
Number.isNaN(maxLength) ||
event.target.value.length !== maxLength ||
!nextField
) {
return;
}
nextField.focus();
})
);
<form>
<div>
<input type="text" maxlength="5" />
</div>
<div>
<div>
<!-- Não há limites para o nível de aninhamento! -->
<input type="text" maxlength="3" />
</div>
</div>
<div>
<input type="text" />
</div>
</form>
I think it ended up being a little simpler too, since we eliminated the use of while
to find the next element, emphasizing simply on the "form and its fields". :)
The functioning of script above is quite simple:
- We captured all the
input
which are part of the form (form
);
- We added a Listener for the event
input
to each of the camps;
- When a field issues the event
input
, we make the necessary checks (explained in the code);
- We find the element by accessing the next
input
through the iteration index (within the forEach
current) added to 1.
Note about the event input
It is important to point out that I changed the event keyup
to the input
, because I think it is more appropriate in that case, since it is issued only when the value of the field is changed, unlike the keyup
, it emits by pressing any key when the element is focused.
There is a gain in the user experience with this exchange, because if one of the fields is already with the character limit, if listening to the event keyup
, the script move to the next field even if I was just browsing the text with, for example, the arrow keys on the keyboard, which is not the most friendly behavior.
Great solution, it is clean and worked perfectly, thank you very much.
– denis