JavaScript - Auto focus next form on max input length
A code example for automatically switching focus to the next form when reaching max character length during form input in JavaScript.
The HTML has multiple textboxes with class "text_form" to process.
<div class="item-container">
<p>The focus moves automatically.</p>
<input type="text" class="text_form" maxlength="4" value="">
<input type="text" class="text_form" maxlength="4" value="">
<input type="text" class="text_form" maxlength="4" value="">
<input type="text" class="text_form" maxlength="4" value="">
</div>
The target textboxes are queried together with querySelectorAll()
.
The input event is implemented on each form with addEventListener()
. It checks if current input length exceeds "maxlength" attribute value, focuses next form if so, otherwise blurs focus from last form.
// Get all textboxes
let text_forms = document.querySelectorAll('.text_form');
for (const [index, text_form] of text_forms.entries()) {
text_form.addEventListener('input', () => {
// Check if maxlength reached
if(text_form.value.length >= text_form.maxLength) {
// If next form exists
if(text_forms[index + 1]) {
// Focus next form
text_forms[index + 1].focus();
}else{
// Blur focus
text_forms[index].blur();
}
}
}, false);
}
TitleJavaScript - Auto focus next form on max input length
CategoryJavaScript
Created
Update
AuthorYousuke.U