22

I have the following html:

<div>
    <input type="text" maxlength="2" class="day-spin-month"></input>
    <span>/</span>
    <input type="text" maxlength="2" class="day-spin-day"></input>
    <span>/</span>
    <input type="text" maxlength="4" class="day-spin-year"></input>
</div>

I am attempting to change focus to the next input. I have it working the following 2 ways.

$('.day-spin-month').on('keyup', function () {
    if (this.value.length >= 2) {
       $(this).next().next().focus();
    }
});
$('.day-spin-day').on('keyup', function () {
    if (this.value.length >= 2) {
       $(this).next().next().focus();
    }
});

fiddle: http://jsfiddle.net/dan_vitch/JbQaN/1/

$('.day-spin-month').on('keyup', function () {
    if (this.value.length >= 2) {
       var test=$(this).next()
       var test2=  $(test).next('input');
       test2.focus();
     }
});
$('.day-spin-day').on('keyup', function () {
    if (this.value.length >= 2) {
        var test=$(this).next()
        var test2=  $(test).next('input');
        test2.focus();
    }
});

fiddle: http://jsfiddle.net/dan_vitch/JbQaN/2/

but it doesnt work this way:

$('.day-spin-month').on('keyup', function () {
    if (this.value.length >= 2) {
       $(this).next('input').focus();
    }
});
$('.day-spin-day').on('keyup', function () {
    if (this.value.length >= 2) {
       $(this).next('input').focus();
    }
});

fiddle: http://jsfiddle.net/dan_vitch/rJwyE/2/

I would like to use the way that is not working. I am not sure if its my selector that incorrect, or the way I understand next()

dan_vitch
  • 4,477
  • 12
  • 46
  • 69

1 Answers1

72

.next() only looks at the next sibling Element in the DOM. IE.

$('.day-spin-month').next('input');

Won't match anything since the next sibling is a span, not an input.

nextAll() looks at all the next siblings, so you want:

$(this).nextAll('input').first().focus();
Paul
  • 139,544
  • 27
  • 275
  • 264