javascript - 如何在每个输入达到最大长度时自动推进焦点

标签 javascript jquery html forms usability

为了提高我正在构建的信用卡表单的可用性,我希望浏览器在用户输入 maxlength 属性中允许的字符后将焦点移至下一个输入输入

目前,我已经使用三个输入字段完成了此操作,但采用的方式非常笨重,无法扩展。请参见下面的代码。

我想做的是编写以下脚本:

If an input with the class autotab has reached it maxlength, move the focus to the next closest input of any class. Additionally (what I have not yet accomplished in my code below) if the value of an input with the class autotab is empty/null, and the backspace/delete key is pressed, the focus should move to the previous closest input of any class`

我的目标是摆脱对为特定字段编写变量的依赖,并稍微自动化此过程。

  $( document ).ready(function() {

    var CCCardFill = 0;
    var CCExpMonthFill = 0;
    var CCExpYearFill = 0;  

    var CCCardMax = 16;
    var CCExpMonthMax =  2;
    var CCExpYearMax =  4;

   $( "input" ).keyup(function() {
      var CCCardFill = $(".CCCard").val().length;
      var CCExpMonthFill = $(".CCExpMonth").val().length;
      var CCExpYearFill = $(".CCExpYear").val().length;

      if (CCCardFill >= CCCardMax) {
        $(".CCExpMonth").focus();
      }
      if (CCExpMonthFill >= CCExpMonthMax) {
        $(".CCExpYear").focus();
      }
      if (CCExpYearFill >= CCExpYearMax) {
        $(".CCName").focus();
      }

  });

  }); 

在这里运行代码笔:http://codepen.io/jeremypbeasley/pen/BoJVRW

最佳答案

您可以使用 maxLengthvalue.length 属性。当它达到最大长度时,您可以简单地使用 next().focus() 聚焦下一个项目。

$( "input[maxlength]" ).keyup(function() {
    var maxLen = this.maxLength;
    var currentLen = this.value.length;

    if (maxLen === currentLen)
    {
        $(this).next().focus(); 
    } 
});

这是 working JSFiddle demo .

如果您的 input 之间还有其他 HTML 元素,您可以使用 nextAll("input").first() 获取最接近的元素与此之后的选择器匹配的元素:

$(this).nextAll("input").first().focus(); 

Another one JSFiddle Demo .

关于javascript - 如何在每个输入达到最大长度时自动推进焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250898/

相关文章:

jquery - 在绝对定位的元素上向左浮动

javascript - 在html元素上设置断点?

html - bootstrap col-div 中的图像大小

javascript - JavaScript 中不赋值的对象返回

javascript - ionic 混合应用程序,在退出时保存应用程序状态/数据

javascript - jQuery在2个动态生成的层下触发事件

javascript - D3.js 在指定 nodeSize 时获取树的渲染尺寸

javascript - 单击切换按钮时如何更改背景颜色?

jquery - localScroll 并缓解滚动问题

HTML/CSS : I can't add some margin's in a span next to a floated element