本文介绍了当每个输入达到最大长度时,如何自动提高焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In order to increase usability for a credit card form I'm building, I want the browser to move the focus to the next input once the user has typed in the characters allowed in the maxlength attribute of the input.

目前,我已经通过三个输入字段完成了此操作,但是非常笨拙,无法扩展.参见下面的代码.

I've accomplished this with three input fields at present but in a very clunky, not scaleable way. See below code.

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

What I would like to do is script the following:

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

My goal is to get away from the dependency on writing variables for specific fields and automate this process a bit.

  $( 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();
      }

  });

  });

可运行的Codepen: http://codepen.io/jeremypbeasley/pen/BoJVRW

Functioning codepen here: http://codepen.io/jeremypbeasley/pen/BoJVRW

推荐答案

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

You can use maxLength and value.length properties. When it reaches the max length, you can simply focus the next item using next().focus().

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

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

这是正在运行的JSFiddle演示.

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

In case if there are other HTML elements between your inputs, you can use nextAll("input").first() to get the closest element matching the selector after this one:

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

另一个JSFiddle演示.

这篇关于当每个输入达到最大长度时,如何自动提高焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:30
查看更多