简体   繁体   English

jQuery的所有所有文本框

[英]jquery each for all text boxes

I am using following script to bind a keypress event on each textbox so that on reaching the maxlength, focus will switch to next input field. 我正在使用以下脚本在每个文本框上绑定一个按键事件,以便在达到最大长度时,焦点将切换到下一个输入字段。 Passing classname as the prarameters to the function. 将类名作为参数传递给函数。

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');
});

As i have mentioned two different input ..it is runnign fine. 正如我已经提到的两个不同的输入..它运行良好。 Butis there any way around so that it will get the classnames and runs through each input box to attach keypress event. Butis周围有任何方法,这样它将获取类名并在每个输入框中运行以附加按键事件。

If I understand you correctly, you want to attach the same event handler to every input field? 如果我理解正确,您想将相同的事件处理程序附加到每个 input字段吗? Just use the selector: 只需使用选择器:

$(':text') 

(for all input type="text" ) fields. (对于所有input type="text" )字段。

So just change 所以只要改变

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

to: 至:

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

If I get you correctly you just need to use type selector for input. 如果我正确地理解了您,则只需使用类型选择器进行输入。 You can also get rid of calling each to iterate thru inputs since binding event to multiply elements interates via them. 您还可以摆脱调用每个输入来迭代输入的麻烦,因为绑定乘法事件会通过它们进行交互。 So you can change your code into something like following: 因此,您可以将代码更改为以下内容:

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

This works fine. 这很好。

HTML 的HTML

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

JS Part 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM