2014-02-18 52 views
0

我正在動態地將4個文本框添加到div標記。目的是獲取IP地址。如下圖所示,我無法在關鍵事件時關注文本字段()

<input type="text" id='ip1' /> 
<input type="text" id='ip2' /> 
<input type="text" id='ip3' /> 
<input type="text" id='ip4' /> 

我在做什麼,

在keyup事件,我檢查它的長度,因此,如果它的「3」我必須專注於下一個文本框。希望你明白我想要做什麼。

jQuery代碼:

$(document).on('keyup','#ip1', function(e){ 
     if($(this).val().length>=3) 
     $("#ip3").focus(); 
}); 
在如果所述第一框長度達到了3位它假設集中第二個文本框#IP2上述代碼

。但它不起作用, ,因爲我已經動態地添加了這些字段。 所以,我的問題是,

如何專注於動態生成的文本字段?

回答

1

加入您還可以添加一個額外屬性的文本字段,所以你必須只定義一個jQuery的事件做所有的工作:

<input type="text" id='ip1' next="ip2" /> 
<input type="text" id='ip2' next="ip3" /> 
<input type="text" id='ip3' next="ip4" /> 
<input type="text" id='ip4' next="-" /> 

JS:

$(document).on('keyup','input', function(e){ 
     if($(this).val().length>=3 && $(this).attr('next') != '-') 
      $('#'+$(this).attr('next')).focus(); 
}); 

http://jsfiddle.net/gp2Mk/

2

您可以嘗試綁定on事件而不是焦點。

Live Demo

變化

$(doucment).on(focus,'#ip2'); 

$('#ip2').focus(); 

而不是硬編碼的事件綁定和重點代碼,你可以使它通用。

$(document).on('keyup','[id^=ip]', function(e){ 
     if($(this).val().length>=3) 
     $(this).next().focus(); 
}); 
+0

非常感謝!!!!!!有用。我一直在搜索谷歌,什麼也沒找到。 – JaiSat

+0

問題在於,例如,您無法將標籤恢復爲之前的文本框來修復錯誤。 – Phylogenesis

+0

不客氣,@JaiSat – Adil

0

可以綁定各個字段的KEYUP「時,他們是動態的

$("#ip3").keyup(function(){ $('#ip4').focus(); });