Skip to content Skip to sidebar Skip to footer

Focus Next Input Once Reaching Maxlength In Different Containers

I want to focus next input once the input field reach the maxlength, but the input fields are in different containers. My Code: The Jquery works for input fields in the same div/

Solution 1:

You could try to get a list of all related input-fields by traversing the DOM up until a certain parent element and looking for each input, determining the current input element and select the next one.

I would propose a different solution: use the tabindex attribute.

div class="date_day"id="input_day">
    <input type="text" maxlength="2" tabindex="1" name="input_day"id="1" value="">
</div>
<div class="date_month"id="input_month">
    <input type="text" maxlength="2" tabindex="2" name="input_month"id="2" value="">
</div>
<div class="date_year"id="input_year">
    <input type="text" maxlength="4" tabindex="3" name="input_year"id="3" value="">
</div>

With this you can create a non-linear movement in regard to the "next" field. The focus can easily be moved to the next one:

$('input').keyup(function(){
  if($(this).val().length==$(this).attr("maxlength")){
        var tabIndex = +$(this).attr('tabindex');
        $('[tabindex=' + (+tabIndex+1) + ']').focus();
  }
});

Solution 2:

Get the index of the current input by searching the matched elements $('input').index(this) Then you can select the next input in the matched elements with .eq(i+1)

$(document).ready(function(){
    $('input').keyup(function(){
        if($(this).val().length==$(this).attr("maxlength")){
            var i = $('input').index(this);
            $('input').eq(i+1).focus();
        }
    });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="date"class="container_date"><divclass="date_day"id="input_day"><inputtype="text"maxlength="2"name="input_day"id="1"value=""></div><divclass="date_month"id="input_month"><inputtype="text"maxlength="2"name="input_month"id="2"value=""></div><divclass="date_year"id="input_year"><inputtype="text"maxlength="4"name="input_year"id="3"value=""></div></div><divid="time"class="container_time"><divclass="time_hour"id="input_hour"><inputtype="text"maxlength="2"name="input_hour"id="1"value=""></div><divclass="time_minute"id="input_minute"><inputtype="text"maxlength="2"name="input_minute"id="2"value=""></div></div>

Post a Comment for "Focus Next Input Once Reaching Maxlength In Different Containers"