【问题标题】:focusing on next input (jquery)专注于下一个输入(jquery)
【发布时间】:2012-05-19 07:51:24
【问题描述】:

我有四个输入,每个输入一个数字。我想要做的是在设置数字后自动将焦点设置到下一个输入。它们都有“输入”类。

这不太奏效:

$(".inputs").keydown(function () {

            $(this).next().focus();
        });

【问题讨论】:

标签: jquery


【解决方案1】:

我建议将每个文本框的 maxlength 设置为 1,并在 val.lengthmaxlength 相同时切换到下一个文本框。

DEMO

$(".inputs").keyup(function () {
    if (this.value.length == this.maxLength) {
      $(this).next('.inputs').focus();
    }
});

编辑:花了一些时间进行以下(未完全测试,但基本测试工作正常)

   1. Allowing just numeric chars  
   2. Allow some control like del, backspace, e.t.c
   3. Backspace on empty textbox will move to prev textbox
   4. charLimit var to dynamically decide how many char you want to restrict.

代码:

$(function() {
    var charLimit = 1;
    $(".inputs").keydown(function(e) {

        var keys = [8, 9, /*16, 17, 18,*/ 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];

        if (e.which == 8 && this.value.length == 0) {
            $(this).prev('.inputs').focus();
        } else if ($.inArray(e.which, keys) >= 0) {
            return true;
        } else if (this.value.length >= charLimit) {
            $(this).next('.inputs').focus();
            return false;
        } else if (e.shiftKey || e.which <= 48 || e.which >= 58) {
            return false;
        }
    }).keyup (function () {
        if (this.value.length >= charLimit) {
            $(this).next('.inputs').focus();
            return false;
        }
    });
});

DEMO

【讨论】:

  • 哇,这太棒了。我将把它与 click() 结合起来,所以当用户选择一个已经填充的文本框时它会重置值。现在,如果用户选择一个填充的输入并键入一个数字,它关注的不是下一个输入,而是它之后的一个(假设所有文本框都已填充)。在理想情况下,我猜它不需要在输入新数字之前删除数字(它会自动替换它)。不过,我可以看到如果使用超过 1 个字符限制来实现这将成为问题。只是我的想法。 click() 无论如何都会为我解决问题:)
  • @domino 很好的发现,但就是放不下它.. 所以这里修复>> jsfiddle.net/skram/qygB2/5
  • 如果输入类型被禁用,我应该修改什么以使其正常工作?
  • 是否接受零值?我试过了,但它不接受。还有,key number是什么意思?
【解决方案2】:

试试这个

jQuery.extend(jQuery.expr[':'], {
    focusable: function (el, index, selector) {
        return $(el).is('a, button, :input,[tabindex]');
    }
});
$(document).on('keypress', 'input,select', function (e) {
    if (e.which == 13) {
        e.preventDefault();
        // Get all focusable elements on the page
        var $canfocus = $(':focusable');
        var index = $canfocus.index(document.activeElement) + 1;
        if (index >= $canfocus.length) index = 0;
        $canfocus.eq(index).focus();
    }
});

【讨论】:

  • 我见过的模仿 按键的最佳解决方案。出于某种原因,$(':focusable') 选择器在没有扩展 jQuery 的情况下为我工作,所以我需要的唯一代码是 //Get all ... 注释后面的四行。
【解决方案3】:

这只会得到下一个元素,不管它是什么。你可能想要:

$(".inputs").keyup(function () {
  $(this).next(".inputs").focus();
});

另外,向上键而不是向下键,否则它会很快改变。

【讨论】:

  • 啊,是的。 keyup 函数能否以某种方式忽略删除/退格键?
  • 其实还有很多其他的键,比如tab键等会导致问题。我想最简单的方法是只过滤数字?
  • @domino 那将是一个不同的问题。
  • 如果你删除或退格数字然后它也将进入下一个输入
【解决方案4】:

这是我用来使输入键充当制表符的代码,即按下 Enter 键时聚焦到下一个元素或按下 shift+Enter 时聚焦上一个元素。

1) 本质上:

tabables = $("*[tabindex != '-1']:visible");
var index = tabables.index(element);
tabables.eq(index + 1).focus();

2)在这里,您是一个封装行为的“类”,考虑到向前和向后以及有效的可聚焦元素。

我希望它有所帮助,如果某些代码适合您的需求,请随时适应您的需求:)

EnterAsTab = function () {
    this.ENTER_KEY = 13;
};

EnterAsTab.prototype.init = function () {
    this.listenOnEnterKey();
};

EnterAsTab.prototype.listenOnEnterKey = function () {

    var me = this;
    $('form input').on('keypress', function (event) {

            if (event.which === me.ENTER_KEY) {

                if (!event.shiftKey)
                    me.findNextFocusableElement(this);
                else
                    me.findPreviousFocusableElement(this);

                event.preventDefault();
            }
        }
    );
};

EnterAsTab.prototype.findNextFocusableElement = function (element) {
    this.findFocusableElement(element, this.increaseIndex);
};

EnterAsTab.prototype.findPreviousFocusableElement = function (element) {
    this.findFocusableElement(element, this.decreaseIndex);
};

EnterAsTab.prototype.findFocusableElement = function (element, callable) {

    var tabables = $("*[tabindex != '-1']:visible");
    var index = tabables.index(element);
    var counter = 1;
    var nextElement = undefined;

    try {

        while (true) {

            if ((nextElement = tabables.eq(index + counter)).length === 0) {
                break;
            }

            if (this.isFocusableElement(nextElement)) {

                var newIndex = callable.call(this, index, counter);
                tabables.eq(newIndex).focus();

                break;
            } else {
                counter++;
            }
        }
    } catch (error) {
        console.log(error);
    }

};

EnterAsTab.prototype.increaseIndex = function (index, counter) {
    return (index + counter);
};

EnterAsTab.prototype.decreaseIndex = function (index, counter) {
    return index - counter;
};

EnterAsTab.prototype.isFocusableElement = function (element) {

    return ['SELECT', 'TEXTAREA'].indexOf(element.prop('tagName')) > -1 ||
        element.is(':text') ||
        element.is(':checkbox') ||
        element.is(':radio');
};

var enterAsTab = new EnterAsTab();
enterAsTab.init();

【讨论】:

    【解决方案5】:

    在搜索和开发之后,我最终进入了一个跨浏览器 sn-p,它可以根据 maxlength(用 1 个字符测试)聚焦具有相同类的下一个输入字段,还可以通过退格按钮重新聚焦:

    Javascript (jquery):

    var codeCharInput = 'input.code-char';
    $(codeCharInput+':first').focus();
    $(codeCharInput).keyup(function(e) {
      if ((e.which == 8 || e.which == 46)) {
        $(this).prev(codeCharInput).focus().val($(this).prev().val());
      } else {
        if (this.value.length == this.maxLength) {
          $(this).next(codeCharInput).focus();
        }
      }
    });
    

    HTML:

    <input type="text" name="chars[]" maxlength="1" class="code-char" />
    <input type="text" name="chars[]" maxlength="1" class="code-char" />
    <input type="text" name="chars[]" maxlength="1" class="code-char" />
    <input type="text" name="chars[]" maxlength="1" class="code-char" />
    

    【讨论】:

      【解决方案6】:

      如果您只想查看下一个输入,但您已经以这样的方式说出分隔符

      <input type="number" pattern="[0-9]*" inputmode="numeric" maxlength="2" placeholder="DD" name="dobday" id="dobday">
      <div class="separator">/</div>
      <input type="number" pattern="[0-9]*" inputmode="numeric" maxlength="2" placeholder="MM" name="dobmonth" id="dobmonth">
      <div class="separator">/</div>
      <input type="number" pattern="[0-9]*" inputmode="numeric" maxlength="4" placeholder="YYYY" name="dobyear" id="dobyear">
      

      您将需要此代码来获取所有下一个项目并确定找到的第一个输入:

      $('input#dobday,input#dobmonth,input#dobyear').on('input', function(e) {
          if (jQuery(this).val().length >= parseInt(jQuery(this).attr("maxlength"), 10)) {
                  if (jQuery(this).attr('id') === 'dobyear') {
                      jQuery(this).blur();
                  } else {
                      jQuery(this).nextAll('input:first').focus();
                  }
          }
      }
      

      【讨论】:

        【解决方案7】:

        使用keyup 例如

        $(".inputs").keyup(function () {
            $(this).next().focus();
        });​
        

        在行动中看到它http://jsfiddle.net/qygB2/

        【讨论】:

        • 如果你删除或退格数字然后它也将进入下一个输入
        【解决方案8】:

        如果您使用的是最新的 jQuery 版本,我强烈建议您使用on 方法。如果你去 jQuery 源代码,你会注意到所有其他事件方法现在都重定向到这个方法,所以为什么不直接使用它:

        $(document).ready(function () {
                $('.inputs').on('keyup', function(){
                    $(this).next().focus();
                })
        });
        

        【讨论】:

          【解决方案9】:

          这将保持焦点在文本框上,在使用 next 之后没有命名类或 id。

           $(this).hide();        
           $(this).next().show();
           $('input[type=text]').focus();
          

          【讨论】:

            【解决方案10】:

            基于@Vega 的回答

            inputs.keydown(function(e) {
                var keys = [8, 9, /*16, 17, 18,*/ 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];
            
                $(this).val('');
            
                if (e.which == 8 && this.value.length == 0) {
                    $(this).prev(inputs).focus();
                } else if ($.inArray(e.which, keys) >= 0) {
                    return true;
                } else if (this.value.length > charLimit) {
                    $(this).next(inputs).focus();
                    return false;
                } else if (e.shiftKey || e.which <= 48 || e.which >= 58) {
                    return false;
                }
            }).keyup (function () {
                if (this.value.length >= charLimit && $(this).next(inputs).attr('type') === 'text') {
                    $(this).next(inputs).focus();
                    return false;
                }
            });
            

            如果用户点击一个已经有值的输入,它将覆盖它,而不是转到下一个输入,它也只会关注文本输入。我有一种情况,我在文本输入旁边有一个提交输入,如果使用退格键可能会意外重定向页面。

            【讨论】:

              【解决方案11】:

              这是满足您所有需求的代码。

              $(".input").keyup(function(e) {
              
              if (e.which == 8 || e.which == 46){ 
                  //backspace / Delete
                  $(this).val('');
                  $(this).prevAll('input:first').focus();
              }
              else
              { 
                  var spcl_arr = ["~","!","@", "#", "$", "%", "^", "&", "*", "(", ")", "+","-", "=", "." ,"/"];
                 if(e.which == 13){ // Enter Kay
                    return false;
                 }
                else if(jQuery.inArray($(this).val(), spcl_arr) !== -1 ){ 
                       $(this).val('');
                       $(this).focus();
                      return false;
                 }else{ 
                     var regex = new RegExp("^[a-zA-Z0-9]+$");
                      var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
                      if (regex.test(str)) { 
                           if (this.value.length == this.maxLength) {
                               $(this).next('.input').focus();
                           }
                      }else{
                          $(this).val('');
                          $(this).focus();
                          return false;
                      }
                  }
              }
              

              });

              【讨论】:

                【解决方案12】:

                这很好用 它还检查中间输入是否已填充

                $(".inputs").keyup( function () {
                
                    if (this.value.length == this.maxLength) {
                    var n=$(this).next('.inputs');
                    n.focus();
                   if(n.val().length==n.prop('maxlength')) n.next('.inputs').focus(); 
                    }
                
                });
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2016-12-05
                  • 2012-10-31
                  • 2011-06-06
                  • 1970-01-01
                  • 2020-10-01
                  相关资源
                  最近更新 更多