2013-03-24 75 views
18

如何在上一個輸入達到其最大長度值時聚焦下一個輸入?聚焦下一個輸入一旦達到最大長度值

a: <input type="text" maxlength="5" /> 
b: <input type="text" maxlength="5" /> 
c: <input type="text" maxlength="5" /> 

如果用戶將文本粘貼比的最大長度時,最好應該波及到下一個輸入。

的jsfiddle:http://jsfiddle.net/4m5fg/1/

我必須強調,我想使用插件,因爲我寧願學習背後的邏輯,不是使用已經存在的東西。感謝您的理解。

+1

@Musa他的目的是「學習背後的邏輯」。 – Antony 2013-03-24 06:06:12

+1

[當輸入文本字段達到最大長度時移動焦點]可能重複(http://stackoverflow.com/questions/1959398/moving-a-focus-when-the-input-text-field-reaches-a - 最大長度) – 2016-06-07 13:36:57

回答

32

沒有jQuery的使用,是一個非常乾淨的實現:

  • 從maxlength屬性讀取。
  • 可以縮放到容器內的任意數量的輸入。
  • 自動找到下一個要輸入的焦點。
  • 沒有jQuery。

http://jsfiddle.net/4m5fg/5/

<div class="container"> 
a: <input type="text" maxlength="5" /> 
b: <input type="text" maxlength="5" /> 
c: <input type="text" maxlength="5" /> 
</div> 

..

var container = document.getElementsByClassName("container")[0]; 
container.onkeyup = function(e) { 
    var target = e.srcElement || e.target; 
    var maxLength = parseInt(target.attributes["maxlength"].value, 10); 
    var myLength = target.value.length; 
    if (myLength >= maxLength) { 
     var next = target; 
     while (next = next.nextElementSibling) { 
      if (next == null) 
       break; 
      if (next.tagName.toLowerCase() === "input") { 
       next.focus(); 
       break; 
      } 
     } 
    } 
    // Move to previous field if empty (user pressed backspace) 
    else if (myLength === 0) { 
     var previous = target; 
     while (previous = previous.previousElementSibling) { 
      if (previous == null) 
       break; 
      if (previous.tagName.toLowerCase() === "input") { 
       previous.focus(); 
       break; 
      } 
     } 
    } 
} 
+0

這僅適用於頁面中的第一個容器。修改它以適用於所有這些是相對微不足道的,但值得指出的是,新手可以使用它。 – Mir 2014-01-23 22:00:52

+0

'var target = e.srcElement || e.target;'幫助我使用您的解決方案。謝謝! – 2016-08-05 09:16:36

+0

如果添加maxlength = 2,則無法編輯輸入字段。 – 2016-12-30 11:59:38

17

你可以看在領域輸入和測試它的值:

$("input").bind("input", function() { 
    var $this = $(this); 
    setTimeout(function() { 
     if ($this.val().length >= parseInt($this.attr("maxlength"),10)) 
      $this.next("input").focus(); 
    },0); 
}); 

Working demo

setTimeout是確保代碼只會在之後運行輸入完成並更新值。綁定input確保大多數類型的輸入都會觸發事件,包括按鍵,複製/粘貼(甚至是從鼠標)並拖動&(儘管在這種情況下,後者不起作用,因爲焦點位於可拖動的位置,而不是可丟棄)。

注意:在一些較舊的瀏覽器上,您可能還需要綁定propertychange


如果用戶將文本粘貼比的最大長度時,最好應該波及到下一個輸入。

爲此,您可能需要使用JavaScript(以便能夠捕獲完整輸入)刪除maxlength屬性,並自行實現該功能。我做了一個small example,相關部分如下:

$("input").each(function() { 
    var $this = $(this); 
    $(this).data("maxlength", $this.prop("maxlength")); 
    $(this).removeAttr("maxlength"); 
}) 

這消除了屬性,但在data將其保存,以便以後可以訪問它。

function spill($this, val) { 
    var maxlength = $this.data("maxlength"); 
    if (val.length >= maxlength) { 
     $this.val(val.substring(0, maxlength)); 
     var next = $this.next("input").focus(); 
     spill(next, val.substring(maxlength)); 
    } 
    else 
     $this.val(val); 
} 

在這裏,最大長度爲邏輯重新引入在JavaScript中,以及收到「丟棄」的一部分,並用它在遞歸調用spill。如果沒有下一個元素,則調用data將返回undefined,循環將停止,因此輸入將在最後一個字段中截斷。

+0

你的小提琴完美的作品和+1,但是,綁定'propertyChange'是強制性的?它似乎工作正常,即使沒有這 – exexzian 2013-03-24 06:57:27

+2

@Bingo根據[這個答案](http://stackoverflow.com/a/9205280/520779),「輸入」是爲Firefox和「propertychange」爲其他人,但事情可能從那以後就改變了(也許每個瀏覽器現在都支持「輸入」)。唯一確定的方法是在不同的環境下進行測試。 (這是財產變更,而不是財產變更 - 我已經更正了我的答案) – mgibsonbr 2013-03-24 07:36:41

+0

這應該是正確的答案。如果你添加maxlength = 2,在接受的答案你不能編輯輸入,但在這個你可以! – 2016-12-30 11:59:04

3

您可以使用普通的JavaScript:

請參閱DEMO

el.value.length檢查字符長度。如果它等於最大值,則使用focus()移至下一個字段。將此函數綁定到鍵盤事件onkeyup,以便在用戶鍵入字符後每次都會觸發該函數。

var a = document.getElementById("a"), 
    b = document.getElementById("b"), 
    c = document.getElementById("c"); 

a.onkeyup = function() { 
    if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
     b.focus(); 
    } 
} 

b.onkeyup = function() { 
    if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
     c.focus(); 
    } 
} 
+0

上使用使用綁定函數可能會產生問題,例如你必須刪除文本框內的一些數字,該事件將不允許刪除,因爲它是一個按鍵。而是使用oninput事件。這將有所幫助 – 2018-01-18 14:01:21

5

如果你打算有很多領域,你可以做這樣的事情。

基本上keyup獲得輸入的長度,然後將其與最大長度比較,如果匹配,則focus到下一個輸入字段。

http://jsfiddle.net/btevfik/DVxDA/

$(document).ready(function(){ 
    $('input').keyup(function(){ 
     if(this.value.length==$(this).attr("maxlength")){ 
      $(this).next().focus(); 
     } 
    }); 
}); 
+0

更新您的代碼以獲得更好的解決方案 - http://jsfiddle.net/ssuryar/DVxDA/224/ - DEMO – 2018-01-18 14:02:47

0

如果要添加輸入文本字段的動態,那麼你可以試試這個。

這將重新將腳本插入DOM並完美工作。

$('body').on('keyup', '#num_1',function(){ 
 
    if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
 
    $('#num_2').focus(); 
 
    } 
 
}) 
 
$('body').on('keyup','#num_2', function(){ 
 
    if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
 
    $('#num_3').focus(); 
 
    } 
 
})
<input type="text" class="form-control" name="number" maxlength="3" id="num_1"> 
 
<input type="text" class="form-control" name="number" maxlength="3" id="num_2"> 
 
<input type="text" class="form-control" name="number" maxlength="4" id="num_3">

0

如果您正在着力打造卡(借記卡/信用卡)數量的輸入類型。然後按照以下步驟清潔易於管理的jQuery版本:

/*.............................................................................................. 
 
* jQuery function for Credit card number input group 
 
......................................................................................................*/ 
 
      // make container label of input groups, responsible 
 
      $('.card-box').on('focus', function(e){ 
 
       $(this).parent().addClass('focus-form-control'); 
 
      }); 
 
      $('.card-box').on('blur', function(e){ 
 
       $(this).parent().removeClass('focus-form-control'); 
 
      }); 
 
      $('.card-box-1').on('keyup', function(e){ 
 
       e.preventDefault(); 
 
       var max_length = parseInt($(this).attr('maxLength')); 
 
       var _length = parseInt($(this).val().length); 
 
       if(_length >= max_length) { 
 
        $('.card-box-2').focus().removeAttr('readonly'); 
 
        $(this).attr('readonly', 'readonly'); 
 
       } 
 
       if(_length <= 0){ 
 
        return; 
 
       } 
 
      }); 
 
      $('.card-box-2').on('keyup', function(e){ 
 
       e.preventDefault(); 
 
       var max_length = parseInt($(this).attr('maxLength')); 
 
       var _length = parseInt($(this).val().length); 
 
       if(_length >= max_length) { 
 
        $('.card-box-3').focus().removeAttr('readonly'); 
 
        $(this).attr('readonly', 'readonly'); 
 
       } 
 
       if(_length <= 0){ 
 
        $('.card-box-1').focus().removeAttr('readonly'); 
 
        $(this).attr('readonly', 'readonly'); 
 
       } 
 
      }); 
 
      $('.card-box-3').on('keyup', function(e){ 
 
       e.preventDefault(); 
 
       var max_length = parseInt($(this).attr('maxLength')); 
 
       var _length = parseInt($(this).val().length); 
 
       if(_length >= max_length) { 
 
        $('.card-box-4').focus().removeAttr('readonly'); 
 
        $(this).attr('readonly', 'readonly'); 
 
       } 
 
       if(_length <= 0){ 
 
        $('.card-box-2').focus().removeAttr('readonly'); 
 
        $(this).attr('readonly', 'readonly'); 
 
       } 
 
      }); 
 
      $('.card-box-4').on('keyup', function(e){ 
 
       e.preventDefault(); 
 
       var max_length = parseInt($(this).attr('maxLength')); 
 
       var _length = parseInt($(this).val().length); 
 
       if(_length >= max_length) { 
 
        return; 
 
       } 
 
       if(_length <= 0){ 
 
        $('.card-box-3').focus().removeAttr('readonly'); 
 
        $(this).attr('readonly', 'readonly'); 
 
       } 
 
      }); 
 
/*.............................................................................................. 
 
* End jQuery function for Credit card number input group 
 
......................................................................................................*/
/* Hide HTML5 Up and Down arrows. */ 
 
           input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button { 
 
            -webkit-appearance: none; margin: 0; 
 
           } 
 
           input[type="number"] { -moz-appearance: textfield; } 
 
           .card-box { 
 
            width: 20%; display: inline-block; height: 100%; border: none; 
 
           } 
 
           
 
           .focus-form-control { 
 
            border-color: #66afe9; outline: 0;-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6); 
 
             box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6); 
 
           }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div class="form-control" style="padding: 0; max-width: 300px; "> 
 
             <input class="card-box card-box-1" type="number" id="CreditCard_CardNumber1" required step="1" minlength="4" maxlength="4" pattern="[0-9]{4}" value="" placeholder="0000" 
 
              onClick="this.setSelectionRange(0, this.value.length)" oninput="this.value=this.value.slice(0,this.maxLength||'');this.value=(this.value < 1) ? ('') : this.value;"/> 
 
             <input class="card-box card-box-2" type="number" id="CreditCard_CardNumber2" readonly required step="1" minlength="4" maxlength="4" pattern="[0-9]{4}" value="" placeholder="0000" 
 
              onClick="this.setSelectionRange(0, this.value.length)" oninput="this.value=this.value.slice(0,this.maxLength||'');this.value=(this.value < 1) ? ('') : this.value;" /> 
 
             <input class="card-box card-box-3" type="number" id="CreditCard_CardNumber3" readonly required step="1" minlength="4" maxlength="4" pattern="[0-9]{4}" value="" placeholder="0000" 
 
              onClick="this.setSelectionRange(0, this.value.length)" oninput="this.value=this.value.slice(0,this.maxLength||'');this.value=(this.value < 1) ? ('') : this.value;" /> 
 
             <input class="card-box card-box-4" type="number" id="CreditCard_CardNumber4" readonly required step="1" minlength="4" maxlength="4" pattern="[0-9]{4}" value="" placeholder="0000" 
 
              onClick="this.setSelectionRange(0, this.value.length)" oninput="this.value=this.value.slice(0,this.maxLength||'');this.value=(this.value < 1) ? ('') : this.value;" /> 
 
            </div>

0

更新btevfik代碼,或的onkeyup onkeydown事件將在標籤導航創建問題。編輯或更改輸入框內的文本將很困難,因爲它將被限制爲maxlength。所以我們可以使用oninput事件來完成任務。

DEMO

HTML

<ul> 
<li>a: <input type="text" maxlength="5" /></li> 
<li>b: <input type="text" maxlength="3" /></li> 
<li>c: <input type="text" maxlength="5" /></li> 
<li>d: <input type="text" maxlength="3" /></li> 
<li>e: <input type="text" maxlength="6" /></li> 
<li>f: <input type="text" maxlength="10" /></li> 
<li>g: <input type="text" maxlength="7" /></li> 
</ul> 

的Javascript

$(document).ready(function(){ 
    $('input').on("input", function(){ 
     if($(this).val().length==$(this).attr("maxlength")){ 
      $(this).next().focus(); 
     } 
    }); 
}); 

CSS

ul {list-style-type:none;} 
li {padding:5px 5px;} 
相關問題