2009-07-17 51 views
3

我已經將autotab.js下載到了我的應用程序中。並且我試圖在我的應用程序中使用它。JQuery中的自動選項卡

我有一個表單,並且我想在填充一個輸入字段後自動標籤到下一個輸入DOM元素。同時,表單只在頁面中生成,所以我不能使用帶有字段標識符的autotab作爲已知因素。如何使用JQuery來做到這一點。

+0

現在說什麼? – peirix 2009-07-17 13:13:12

回答

5

如果無法將ID添加到輸入中,則需要爲這些屬性找到不同的選擇器。

如果您打算髮送此數據,您可能會爲這些標籤命名。然後,你可以使用以下選擇按名稱的下一個輸入匹配:

$('input[name=nextInputName]') 

否則,你總能找到使用children()parent()方法調用組合的下一個元素,爲了從當前輸入遍歷到下一個。

我個人認爲,最簡單的解決方案是分配ids,即使在jQuery中,如果你不能在HTML中執行它:這將使自動聚焦更容易。

var counter = 0; 
$('input').each(function() { 
    if (!$(this).attr('id')) { 
     $(this).attr('id', 'autofocus' + counter); 
     counter += 1; 
    } 
}); 

您可以更改選擇器以跳過某些您不希望具有自動對焦功能的元素。

話,甚至可以記下自動對焦在自己的幾行:

$('input[id^=autofocus]').keyup(function() { 
    if ($(this).val().length === $(this).attr('maxlength')) { 
     var id = $(this).attr('id').match(/^autofocus(\d+)$/[1]); 
     var nextId = Number(id) + 1; 
     $('#autofocus' + nextId).focus() 
    } 
}); 
1

此函數讀取的最大長度上的輸入設置。你可以使用$('input.autotab')來調用它。autotab();

jQuery函數如下:

$.fn.autotab = function(){ 
$(this).keyup(function(e){ 
     switch(e.keyCode){ 
       // ignore the following keys 
       case 9: // tab 
         return false; 
       case 16: // shift 
         return false; 
       case 20: // capslock 
         return false; 
       default: // any other keyup actions will trigger 
         var maxlength = $(this).attr('maxlength'); // get maxlength value 
         var inputlength = $(this).val().length; // get the length of the text 
         if (inputlength >= maxlength){ // if the text is equal of more than the max length 
           $(this).next('input[type="text"]').focus(); // set focus to the next text field 
         } 
     } 
}); 

};

+0

謝謝,這對我很好。 – weston 2012-05-25 05:50:29

0

這就是我能夠獲得自動標籤功能爲我工作。希望它能幫助別人。

<input type="tel" id="areaPhone" name="areaPhone" data-next-field="prefixPhone" maxlength="3"> 
<input type="tel" id="prefixPhone" name="prefixPhone" data-next-field="suffixPhone" maxlength="3"> 
<input type="tel" id="suffixPhone" name="suffixPhone" maxlength="4"> 

/* jQuery的就緒*/

$('input[type=tel]').keyup(function() { 

/* Steps: 
    1. Get length values from field 
    2. Get maxlength value of field and convert to integer 
    3. Get data-next-field value of next field to focus on 
    4. Concat a hashtag and data value of field to jump to 
*/ 

var fieldVal = $(this).val(), 
    fieldLen = fieldVal.length, 
    fieldMaxLen = parseInt($(this).attr('maxlength')), 
    jumpToField = $(this).data('next-field'), 
    nextFieldID = '#' + jumpToField; 

// Check if field length and maxlength are equal 
if (fieldMaxLen === fieldLen) { 

    // Check if data-next-field attribute is undefined or null 
    if (jumpToField === undefined || jumpToField === null) { 

    } else { 
     $(nextFieldID).focus(); 
    } 
} 

});