[英]jquery each for all text boxes
我正在使用以下脚本在每个文本框上绑定一个按键事件,以便在达到最大长度时,焦点将切换到下一个输入字段。 将类名作为参数传递给函数。
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');
});
正如我已经提到的两个不同的输入..它运行良好。 Butis周围有任何方法,这样它将获取类名并在每个输入框中运行以附加按键事件。
如果我理解正确,您想将相同的事件处理程序附加到每个 input
字段吗? 只需使用选择器:
$(':text')
(对于所有input type="text"
)字段。
所以只要改变
$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {
至:
$(':text').each(function() {
如果我正确地理解了您,则只需使用类型选择器进行输入。 您还可以摆脱调用每个输入来迭代输入的麻烦,因为绑定乘法事件会通过它们进行交互。 因此,您可以将代码更改为以下内容:
var autoFocusPhoneFields = function () {
$('input:text').keypress(function() {
if(this.value.length == $(this).attr('maxlength'))
$(this).next('input').focus();
});
}
$(autoFocusPhoneFields);
这很好。
的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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.