2017-01-10 39 views
1

我有一个表单,只有一个由条形码扫描器填充的输入。我试图使用JS或JQuery来提交表单,只有当输入的内容是7个字符。我希望它的形式为AUTO提交,无需用户点击提交。我看了很多例子,但还没有找到一个可行的解决方案。X字符后自动提交表格

这里是我的尝试:

<form action="PupListMobile.php" id="my_form" method="get"> 
    <label for="text-1"></label> 
    <input type="text" autofocus name="sID" id="sID" value="" id="my_button" placeholder="CLICK TO SCAN:"> 
    <input type="hidden" name="lane" value="1" /> 
    <input id="subHere"type="submit" value="Submit" /> 

</form> 

的Jquery:

$('#sID').keyup(function(){ 
    if(this.value.length ==7){ 
    $('#subHere').click(); 
    } 
}); 

$(document).ready(function() { 
    $(window).keydown(function(event){ 
    if(event.keyCode == 13) { 
     event.preventDefault(); 
     return false; 
    } 
    }); 
}); 

回答

1

我将与以下几点入手:

  1. maxlength="7"添加到文本输入,因为您使用的是keyup(..),因此您无法按住某个键以强制输入超过7个字符的文本
  2. 使用jquery函数检测长度,然后提交输入的表单

设置最大长度

<input type="text" autofocus name="sID" id="sID" value="" 
    id="my_button" placeholder="CLICK TO SCAN:" maxlength="7" /> 

自动提交表单

$(function() { 
 
     var $id = $('#sID'); 
 
     $id.keyup(function(e) { 
 
     if ($id.val().length >= 7) { 
 
      $(this.form).submit(); 
 
     } 
 
     }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<form action="PupListMobile.php" id="my_form" method="get"> 
 
    <label for="text-1"></label> 
 
    <input type="text" autofocus name="sID" id="sID" value="" id="my_button" placeholder="CLICK TO SCAN:" maxlength="7" /> 
 
    <input type="hidden" name="lane" value="1" /> 
 
    <input id="subHere"type="submit" value="Submit" /> 
 

 
</form>

+0

这个工作。谢谢!我花了数小时寻找修复。 –

1
$(function(){ 
    $('#sID').keyup(function(){ 
     if(this.value.length ==7){ 
      alert(123); 
     $('#subHere').click(); 
     } 
    }); 
}) 

您可以测试这个