2016-03-02 49 views
0

在輸入字符數maxlength後,我需要關注下一個輸入。問題是,下一個輸入並不總是一個兄弟:找到下一個與jquery時沒有兄弟

jQuery("input").on('input', function() { 
 
    if (jQuery(this).val().length == jQuery(this).attr('maxlength')) { 
 
    jQuery(this).next("input").focus(); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
When you have write 4 char, the focus have to switch to the next input: 
 
<div> 
 
    OK 
 
    <input maxlength="4"> 
 
    <input maxlength="4"> 
 
</div> 
 
KO 
 
<input id="inputWithTheIssue">

回答

4

不能使用.next()功能,因爲所有的inputs都沒有兄弟姐妹。因此,您需要在整組輸入控件中找到當前輸入的index,並將其增加1以查找下一個出現的輸入元素。

jQuery("input").on('input',function() { 
      if(jQuery(this).val().length == jQuery(this).attr('maxlength')) { 
       var currIndex = $(this).index(); // gets the index value w.r.t the other input controls 
       $('input').eq(currIndex + 1).focus(); 
      } 
     }); 

工作例如:https://jsfiddle.net/DinoMyte/uhpn7pyx/2/

+2

也許一個解釋可以幫助OP和未來的讀者 – Adjit

+0

當'currIndex + 1'沒有返回一個jQuery對象,然後嘗試調用'focus()'時,這會拋出一個錯誤嗎? –

+0

不,它不會。如果您試圖訪問它的屬性或屬性值,它只會拋出未定義的錯誤。事件是好的。 – DinoMyte

1

有幾個的,你需要做的事情。

  1. 將[type =「text」]屬性添加到您的元素。
  2. 使用正確的父元素來獲取子輸入。 (我使用的文檔作爲家長可能不適合您的方案有利。)

var $check = $(document).find('input[type="text"]'); 
 
jQuery("input").on('input', function() { 
 
    if (jQuery(this).val().length == jQuery(this).attr('maxlength')) { 
 
    $check.eq($check.index(this) + 1).focus(); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
When you have write 4 char, the focus have to switch to the next input: 
 
<div> 
 
    OK 
 
    <input maxlength="4" type="text"> 
 
    <input maxlength="4" type="text"> 
 
</div> 
 
KO 
 
<input id="inputWithTheIssue" type="text">

+0

輸入不帶類型屬性默認情況下視爲文本。所以你不需要明確地聲明它。 – DinoMyte

+0

@DinoMyte但是我們不能使用這個'input [type =「text」]'來選擇它們。 – RRK

+0

只有當DOM具有其他輸入類型時,它纔會起作用。在OP問的問題中,這不是必需的。 – DinoMyte

0

你被明確要求一個jQuery的解決方案,但你可以在純真的很容易做到這一點JavaScript,而不需要合併任何庫。

function inputChanged(element, index, array) { 
 
    element.oninput = function() { 
 
    if (element.value.length >= 4 && (index < array.length - 1)) { 
 
     array[index + 1].focus(); 
 
    } 
 
    } 
 
} 
 

 
Array.from(document.getElementsByTagName('input')).forEach(inputChanged);
<div> 
 
    <input maxlength="4"/> 
 
    <input maxlength="4"/> 
 
</div> 
 
<input id="inputWithTheIssue"/>

我要做的是在這裏調用inputChanged功能文檔中的每個input。這個函數參數:

  • element持有調用它元素,
  • index持有這當中所有的人input調用此函數的信息,並
  • array存儲所有這些input秒。

內部用戶的輸入這個功能我檢查:

  • 給定元素有4個或更多的價值,並
  • 如果我們沒有在最後的位置在所有的input S的。

如果是這樣,我們將重點關注數組中的下一個元素。

即使你想用jQuery來解決你的問題,我希望你或者別人也能找到這個答案。

相關問題