Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

javascript - 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:

    $(document).ready(function(){
        $('input').keyup(function(){
            if($(this).val().length==$(this).attr("maxlength")){
                $(this).next().focus();
            }
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date" class="container_date">
    <div class="date_day" id="input_day">
        <input type="text" maxlength="2" name="input_day" id="1" value="">
    </div>
    <div class="date_month" id="input_month">
        <input type="text" maxlength="2" name="input_month" id="2" value="">
    </div>
    <div class="date_year" id="input_year">
        <input type="text" maxlength="4" name="input_year" id="3" value="">
    </div>
</div>


    <div id="time" class="container_time">
        <div class="time_hour" id="input_hour">
            <input type="text" maxlength="2" name="input_hour" id="1" value="">
        </div>
        <div class="time_minute" id="input_minute">
            <input type="text" maxlength="2" name="input_minute" id="2" value="">
        </div>
    </div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...