1

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.

Michael
  • 3,935
  • 4
  • 24
  • 25
  • possible duplicate http://stackoverflow.com/questions/10539113/focusing-on-next-input-jquery – Ammar Nov 25 '14 at 23:21
  • The events fire when I want them to. The problem is the focus is not changing. My temporary fix has been to bind keyup events to each field individually and set the focus to fields manually using their IDs. – Michael Nov 25 '14 at 23:26

1 Answers1

3

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>
PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • 1
    Great! I have provided some explanation; let me know if you have any specific questions. ... in short the input elements are NOT siblings; that's why your approach did not work. – PeterKA Nov 25 '14 at 23:31