Auto tab to next input field when fill 4 characters
Your code works fine, however your input elements are set as type="number"
. Non-numeric content is ignored, so if you enter "abcd", for example, the input's value
is empty (meaning a length
of 0
). If you enter "1234" on the other hand, the input's value is 1234
.
If you want your code to fire when non-numeric content is entered, simply change each input's type to text
.
<input class="inputs" type="text" maxlength="4" />
JSFiddle demo.
Note that I've also removed the duplicate class
attribute from each of your elements in that example, too.
As krish has mentioned in the comments on your question, there is an issue with your code in that the last input
element will continue to accept more than 4 characters. To fix this, put a check in place to ensure that there is a next('.inputs')
element:
if (this.value.length == this.maxLength) {
var $next = $(this).next('.inputs');
if ($next.length)
$(this).next('.inputs').focus();
else
$(this).blur();
}
JSFiddle demo.
Perhaps you neglected to enclose your code in DOM ready. Jsfiddle encloses your code in $(window).load(function() { .....})
and that's why it's working. So on your own page use:
$(function() {
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
});
In the jsfiddle you can confirm that by selecting No wrap - in <head>
and then click run. The code will not work. But if you use the above which is enclosed in DOM ready, it works.