2011-08-25 44 views
1

我正在使用以下脚本绑定每个文本框上的按键事件,以便在达到最大长度时,焦点将切换到下一个输入字段。传递类名作为函数的参数。jquery每个文本框

function autoFocusPhoneFields(txtbox1ID,txtbox2ID) { 
    $('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() { 
     $(this).bind('keypress', function(){ 
     if(this.value.length == $(this).attr('maxlength')) { 
      $(this).next('input').focus(); 
     } 
    }); 
}); 
} 
    $(document).ready(function(){ 
    autoFocusPhoneFields('mobileprefix','mobilecode'); 
}); 

正如我所提到的两个不同的输入.. it runnign罚款。 Butis有任何方法可以获得类名并通过每个输入框运行以附加按键事件。

回答

3

如果我正确理解你,你想附加相同的事件处理程序到input字段?只需使用选择:

$(':text') 

(所有input type="text")领域。

所以只是改变

$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() { 

到:

$(':text').each(function() { 
+2

如果你使用'$( '输入[类型= “文本”]''),jQuery的可以利用的本地浏览器的方法。 –

+0

它会给你相同的结果,但':text'不是一个CSS选择器,它是一个jQuery伪选择器。如果您使用有效的CSS选择器,jQuery将直接使用本地浏览器方法。出于性能原因,有效的CSS选择器是首选。 –

+0

你是对的。 jQuery网站上的语法是$('[type = text]')。 http://api.jquery.com/text-selector/ –

2

如果我让你正确,您只需要使用类型选择输入。您也可以摆脱每次调用以通过绑定事件来迭代输入,以通过它们来乘以元素交互。所以你可以改变你的代码,如下所示:

var autoFocusPhoneFields = function() { 
    $('input:text').keypress(function() { 
     if(this.value.length == $(this).attr('maxlength')) 
      $(this).next('input').focus();    
    }); 
} 
$(autoFocusPhoneFields); 
1

这工作正常。

HTML

<input id="one" class="inp" maxlength="5" /> 
<input id="two" class="inp" maxlength="3" /> 
<input id="three" class="inp" maxlength="2" /> 

JS部分

$(function(){ 
    var onpress = function(){ 
     var val = $(this).val(); 
     var next_input = $(this).next('input'); 
     var mx = $(this).attr('maxlength'); 
     try { 
      mx = Number(mx); 
      if (next_input.length >= 1 && val.length >= mx){ 
       next_input.focus(); 
      } 
     } catch(x){} 

    } 

    $('input.inp').bind('keypress', onpress); 
});