How to focus next input field on keypress
How about:
$('input.mobile-verify.pass').on('keyup', function() {
if ($(this).val()) {
$(this).next().focus();
}
});
So on key up, if there is a value, focus the next. Using keyup allows you to validate the contents rather than skipping right away. They might switch to number mode on iOS for example which would trigger the focus if you simply use keypress.
Codepen: http://codepen.io/anon/pen/qaGKzk
Use .next()
and .trigger()
:
$(".mobile-verify.pass").on("keypress", function(e){
$(this).next().trigger("focus");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="mobile-verify pass" name="code[]" />
<input type="number" class="mobile-verify pass" name="code[]" />
<input type="number" class="mobile-verify pass" name="code[]" />
<input type="number" class="mobile-verify pass" name="code[]" />
Side note: Find another solution for the maxlength
attribute functionality, as per maxlength ignored for input type=“number”
JavaScript and events keypress
and focus
and also key numbers validation:
document
.querySelectorAll('.mobile-verify.pass')
.forEach(el =>
el.onkeyup = e => {
if (e.target.value) {
el.nextElementSibling.focus()
}
}
)
<input type="number" class="mobile-verify pass" maxlength="1" name="code[]" />
<input type="number" class="mobile-verify pass" maxlength="1" name="code[]" />
<input type="number" class="mobile-verify pass" maxlength="1" name="code[]" />
<input type="number" class="mobile-verify pass" maxlength="1" name="code[]" />