Reputation: 883
If I have three input tags separated by span tags, like this
<input class="some-class" type="number" maxlength="4">
<span class="bull">•</span>
<input class="some-class" type="number"maxlength="4">
<span class="bull">•</span>
<input class="some-class" type="number" maxlength="4">
How do I select the next input tag using jQuery in order to do something? My jQuery code below does not select the next input tag using .next()
function
$(':input').keyup(function (e) {
if ($(this).val().length == $(this).attr('maxlength')) {
$(this).next(':input').focus();
}
});
Upvotes: 1
Views: 114
Reputation: 9060
You also can use the .siblings(), to find the input that sibling to its :
$(':input').keyup(function(e){
if($(this).val().length==$(this).attr('maxlength'))
$(this).siblings('input').focus();
// do something
});
Upvotes: 1
Reputation: 144689
You could use the .index()
and .eq()
methods:
var $inputs = $(':input');
$inputs.keyup(function(e) {
if ( this.value.length == this.getAttribute('maxlength') )
$inputs.eq( $inputs.index(this) + 1 ).focus();
});
Upvotes: 1
Reputation: 240928
Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
It's because the .next()
method returns the immediately following sibling element. Since the immediate following sibling is a span
, nothing is selected.
One option would be to use the .nextAll()
method instead. Then chain .first()
in order to select the first match:
$(this).nextAll(':input').first().focus();
$(':input').keyup(function (e) {
if (this.value.length == $(this).attr('maxlength')) {
$(this).nextAll(':input').first().focus();
}
});
Upvotes: 1