Reputation: 4025
I have the following HTML:
<table>
<tr><td><input id="startMonth" placeholder="MM" class="dateInput"></td><td>/</td><td><input id="startDay" placeholder="DD" class="dateInput"></td><td>/</td><td><input id="startYear" placeholder="YY" class="dateInput"></td></tr>
<tr><td><input id="endMonth" placeholder="MM" class="dateInput"></td><td>/</td><td><input id="endDay" placeholder="DD" class="dateInput"></td><td>/</td><td><input id="endYear" placeholder="YY" class="dateInput"></td></tr>
</table>
With the following jQuery script:
$('.dateInput').on('keyup', function () {
if (this.value.length >= 2) {
$(this).nextAll('input').first().focus();
}
})
The event fires, but focus is not changed. I tried removing the tags from between the form fields, and that didn't help either.
Upvotes: 1
Views: 148
Reputation: 24648
Problem is .nextAll()
is not the right method, and .next()
wouldn't be either. These methods operate on sibling elements. In this case the inputs are children of td
elements which are in turn children of tr
.
The index()
and .eq()
method would be helpful here. However, you may want to tweak the logic for the very last element, as there's no next element to jump to.
$('.dateInput').on('keyup', function () {
if (this.value.length >= 2) {
var index = $('.dateInput').index( this ) + 1;
$('.dateInput').eq( index ).focus();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr><td><input id="startMonth" placeholder="MM" class="dateInput"></td><td>/</td><td><input id="startDay" placeholder="DD" class="dateInput"></td><td>/</td><td><input id="startYear" placeholder="YY" class="dateInput"></td></tr>
<tr><td><input id="endMonth" placeholder="MM" class="dateInput"></td><td>/</td><td><input id="endDay" placeholder="DD" class="dateInput"></td><td>/</td><td><input id="endYear" placeholder="YY" class="dateInput"></td></tr>
</table>
Upvotes: 3