簡體   English   中英

在maxlength reach或backspace keypress上關注next / prev輸入

[英]Focus next/prev input on maxlength reached or backspace keypress

我看過HTML表單,光標自動從一個輸入字段移動到另一個輸入字段,並使用退格鍵移動到前一個字段。 它適用於需要粘貼跨越多個輸入字段的序列號,或者鍵入或粘貼多個字段輸入中的數字時的情況。

 $(document).ready(function() { $('.Box').on("keyup", function(e) { var Length = $(this).attr("maxlength"); if ($(this).val().length >= parseInt(Length)) { $(this).removeClass("productkey1").addClass("productkey2"); $(this).next('.Box').focus(); } }); }); $(document).ready(function() { $('.Box').on("keydown", function(e) { var Length = $(this).attr("maxlength"); if ($(this).val().length > parseInt(Length)) { $(this).removeClass("productkey2").addClass("productkey1"); $(this).prev('.Box').focus(); } }); }); 
 .Box:focus { border: thin solid #FFD633; -webkit-box-shadow: 0px 0px 3px #F7BB2E; -moz-box-shadow: 0px 0px 3px #F7BB2E; box-shadow: 0px 0px 3px #F7BB2E; } .Box { height: 15px; width: 4%; text-align: justify; letter-spacing: 5px; padding: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div> <sapn>Enter Key Code :</sapn> <input class="Box productkey1" style="width: 35px;" type="password" name="number1" maxlength="1"> <input class="Box productkey1" style="width: 35px;" type="password" name="number2" maxlength="1"> <input class="Box productkey1" style="width: 35px;" type="password" name="number3" maxlength="1"> <input class="Box productkey1" style="width: 35px;" type="password" name="number4" maxlength="1"> </div> 

您可以通過在按下退格鍵時檢查當前輸入中文本的length為零來實現此目的:

 $(document).ready(function() { $('.Box').on("keyup", function(e) { var $input = $(this); if ($input.val().length == 0 && e.which == 8) { $input.toggleClass("productkey2 productkey1").prev('.Box').focus(); } else if ($input.val().length >= parseInt($input.attr("maxlength"), 10)) { $input.toggleClass("productkey1 productkey2").next('.Box').focus(); } }); }); 
 .Box:focus { border: thin solid #FFD633; -webkit-box-shadow: 0px 0px 3px #F7BB2E; -moz-box-shadow: 0px 0px 3px #F7BB2E; box-shadow: 0px 0px 3px #F7BB2E; } .Box { height: 15px; width: 50px; text-align: justify; letter-spacing: 5px; /*CSS letter-spacing Property*/ padding: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div> <sapn>Enter Key Code :</sapn> <input class="Box productkey1" type="password" name="number1" maxlength="4"> <input class="Box productkey1" type="password" name="number2" maxlength="4"> <input class="Box productkey1" type="password" name="number3" maxlength="4"> <input class="Box productkey1" type="password" name="number4" maxlength="4"> </div> 

另請注意,我將on()邏輯整理到單個事件處理程序中,並使用toggleClass()在單個調用中修改這兩個類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM