Reputation: 13
I'm creating a form, and part of this form is three fields which require two numbers to be entered in to each. When someone has entered two digits into the first, I'd like them to move automatically onto the second field, and then to the third when they have entered two numbers into the second field.
Here is my code - unfortunately it isn't working, and I'd be really grateful for any help:
<div class="en__field__element en__field__element--tripletext">
<div class="en__field__item">
<input id="en__field_supporter_NOT_TAGGED_11" type="text" class="en__field__input en__field__input--tripletext" name="supporter.NOT_TAGGED_11" value="" maxlength="2">
</div>
<div class="en__field__item">
<input type="text" class="en__field__input en__field__input--tripletext" name="supporter.NOT_TAGGED_11" value="" maxlength="2">
</div>
<div class="en__field__item">
<input type="text" class="en__field__input en__field__input--tripletext" name="supporter.NOT_TAGGED_11" value="" maxlength="2">
</div>
</div>
$(".en__field__input.en__field__input--tripletext").keyup(function () {
if (this.value.length == this.maxLength) {
var $next = $(this).next('.en__field__input.en__field__input--tripletext');
if ($next.length)
$(this).next('.en__field__input.en__field__input--tripletext').focus();
else
$(this).blur();
}
});
Upvotes: 1
Views: 1640
Reputation: 5967
.next()
only looks within siblings. In your case the field is inside the parent's sibling so you'd have to get the parent's next sibling to find the next input.
On a side note, you might want to skip certain key codes (e.g. arrow keys) in the keyup event.
Example:
$(".en__field__input.en__field__input--tripletext").keyup(function() {
if (this.value.length == this.maxLength) {
$(this)
.blur()
.parent()
.next()
.children('.en__field__input.en__field__input--tripletext')
.focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="en__field__element en__field__element--tripletext">
<div class="en__field__item">
<input id="en__field_supporter_NOT_TAGGED_11" type="text" class="en__field__input en__field__input--tripletext" name="supporter.NOT_TAGGED_11" value="" maxlength="2">
</div>
<div class="en__field__item">
<input type="text" class="en__field__input en__field__input--tripletext" name="supporter.NOT_TAGGED_11" value="" maxlength="2">
</div>
<div class="en__field__item">
<input type="text" class="en__field__input en__field__input--tripletext" name="supporter.NOT_TAGGED_11" value="" maxlength="2">
</div>
</div>
Upvotes: 2