Reputation: 500
I'm using the following jQyery code to auto focus on the next input field when the previous field has reached it maxLength
value. However it won't place the focus on the next input field.
$(".input_focus input").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.input_focus input').focus();
}
});
I guess that it might have something to do with the .next
selector which should target the next sibling. But as for as I know the next .input_focus input
is the sibling of the previous one.
This is the markup for a part of the form that I'm using:
<li id='field_8_8' class='input_focus'>
<label class='gfield_label' for='input_8_8' >My label<span class='gfield_required'>*</span></label>
<div class='ginput_container ginput_container_text'>
<input name='input_8' id='input_8_8' type='text' value='' class='small' maxlength='4' tabindex='5' placeholder='1234' aria-required="true" aria-invalid="false" />
</div>
</li>
<li id='field_8_10' class='input_focus'>
<label class='gfield_label' for='input_8_10' >My other label<span class='gfield_required'>*</span></label>
<div class='ginput_container ginput_container_text'>
<input name='input_10' id='input_8_10' type='text' value='' class='small' maxlength='2' tabindex='6' placeholder='AB' aria-required="true" aria-invalid="false" />
</div>
I'm not a jQuery expert by any means so I'm probably overlooking something. Any help is much appreciated.
Upvotes: 1
Views: 41
Reputation: 337590
The issue is because the input
elements are not siblings and the selector you provide to next()
, which is intended for sibling filtering, is actually trying to target the child of another parent element.
To fix this you need to amend the DOM traversal slightly. You can use closest()
to get the parent li
, then use next()
to get its sibling li
, then finally find()
to target the input
:
$(".input_focus input").keyup(function() {
if (this.value.length == this.maxLength) {
$(this).closest('li.input_focus').next('li.input_focus').find('input').focus();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="field_8_8" class="input_focus">
<label class="gfield_label" for="input_8_8">My label<span class="gfield_required">*</span></label>
<div class="ginput_container ginput_container_text">
<input name="input_8" id="input_8_8" type="text" value="" class="small" maxlength="4" tabindex="5" placeholder="1234" aria-required="true" aria-invalid="false" />
</div>
</li>
<li id="field_8_10" class="input_focus">
<label class="gfield_label" for="input_8_10">My other label<span class="gfield_required">*</span></label>
<div class="ginput_container ginput_container_text">
<input name="input_10" id="input_8_10" type="text" value="" class="small" maxlength="2" tabindex="6" placeholder="AB" aria-required="true" aria-invalid="false" />
</div>
</li>
</ul>
Upvotes: 1