如何在每个输入达到最大长度时自动提前聚焦

时间:2015-10-21 04:22:14

标签: javascript jquery html forms usability

为了提高我正在构建的信用卡表单的可用性,我希望一旦用户输入maxlength属性中允许的字符,浏览器就会将焦点移动到下一个输入{1}}。

我目前已经用三个输入字段完成了这个,但是以一种非常笨重,不可扩展的方式。见下面的代码。

我想做的是编写以下内容:

  

如果具有autotab类的输入已达到maxlength,则将焦点移动到任何类的下一个最接近的输入。另外(我在下面的代码中还没有完成)如果autotab类的输入值为空/ null,并且按下退格/删除键,焦点应该移动到任何类的前一个最接近的输入

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

input

在此处运行codepen:http://codepen.io/jeremypbeasley/pen/BoJVRW

5 个答案:

答案 0 :(得分:2)

您可以使用NSString *responseStringCommunication=[[NSString alloc]initWithData:MutableData encoding:NSUTF8StringEncoding]; Parser *parser=[[Parser alloc]init]; NSMutableArray *array=[parser parse:responseStringCommunication]; maxLength属性。当它达到最大长度时,您可以使用value.length简单地聚焦下一个项目。

next().focus()

这是working JSFiddle demo

如果您的$( "input[maxlength]" ).keyup(function() { var maxLen = this.maxLength; var currentLen = this.value.length; if (maxLen === currentLen) { $(this).next().focus(); } }); 之间存在其他HTML元素,则可以使用input获取最接近的元素与此选择器匹配

nextAll("input").first()

Another one JSFiddle Demo

答案 1 :(得分:1)

在您的情况下,您可以这样做:

$(this).next("input").focus();

替换您的.focus()项目。这将从您当前的元素移动到DOM中的下一个input元素。

答案 2 :(得分:0)



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

$("input").keyup(function() {
  var value = $(this).val().length;
  var max = $(this).attr('maxlength')
  console.log(value);
  console.log(max);
  if (value == max) {
    console.log('equal');
    $("input").next().focus();
  }
});




尝试获取attr maxlength并将其与val()。length进行比较,如果等于下一个输入

答案 3 :(得分:0)

<script>
function autotab(current,to){
    if (current.getAttribute && 
      current.value.length==current.getAttribute("maxlength")) {
        to.focus() 
        }
}
</script>

<b>Enter your phone number ex (1-888-555-1234):</b>
<form name="telephone">
<input type="text" name="phone0" 
    size=2 onKeyup="autotab(this, document.telephone.phone1)" maxlength=1>- 
<input type="text" name="phone1" 
    size=4 onKeyup="autotab(this, document.telephone.phone2)" maxlength=3>- 
<input type="text" name="phone2" 
    size=4 onKeyup="autotab(this, document.telephone.phone3)" maxlength=3>- 
<input type="text" name="phone3" size=5 maxlength=4>
</form>

以下是我将如何实现这一目标。每个元素使用onKeyup事件来调用autotab函数,发送自己的对象,然后关注以下元素的对象,然后测试maxlength。

答案 4 :(得分:0)

您想要查看触发事件的输入。事件处理程序中的this是想要的元素

var $inputs = $( "input" )

$inputs.keyup(function() {
   var $input = $(this), max = $input.attr('maxlength');
   if(max){
      max = parseInt(max,10);
      if(this.value && this.value.length == max){
           $inputs( $inputs.index(this) +1).focus()
      }
   }

})