自动提交表单

时间:2016-03-15 12:10:58

标签: javascript php html forms

我想在输入中填写4个数字时自动提交表单。 我目前只有一个基本的HTML格式:

<form action="send.php" method="POST">
   <input type="number" maxlength="4">
</form>

现在我希望如果你达到maxlength它会自动提交表单,所以你不必点击输入或提交。 有没有办法做到这一点?

3 个答案:

答案 0 :(得分:1)

你可以这样做:

  1. 将keyup侦听器添加到输入
  2. 检查其中的值的长度
  3. &#13;
    &#13;
    for (idx=0;idx<childs.length;++idx) {
        if (typeof(obj[childs[idx]]) == 'object' != childs[idx] != "$xml") {
            out += this.dump( obj[childs[idx]], childs[idx], nLevels );
        } else {
            out += sPre + '\t' + childs[idx] + '="' + obj[childs[idx]].toString() + '"\n';
        }
    }
    
    &#13;
    function checkField(input) {
      if(input.value.length == 4) {
        document.forms[0].submit();
      }
    }
    &#13;
    &#13;
    &#13;

答案 1 :(得分:1)

试试这个 - 使用键启动触发器并使用jQuery - 也可以获得函数中的maxlength,因为它可能会在将来发生变化。我还在那里发出警告,以便你可以在片段中看到效果 - 只是为了在SO中。

&#13;
&#13;
    
    //js (assuming use of jQuery)
    $('[name=sampleInput]').on('keyup',function(){
    var maxlen=$(this).attr('maxlength');
    var len=$(this).val();
    if(len.length == maxlen){alert('form submitted');$('[name=sampleForm]').submit();}
    })
    
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form name="sampleForm" action="send.php" method="POST">
    <input name="sampleInput" type="number" maxlength="4">
    </form>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以定义oninput属性:

<input type="number" maxlength="4" oninput="if(this.value.length==4) this.form.submit();">

如果使用鼠标在输入框中粘贴4位数值(因此不会发生键盘事件),这也适用。

您可以使用script代码移动代码,捕获oninput事件:

<form action="send.php" method="POST">
    <input type="number" maxlength="4">
</form>
<script>
    var input = document.querySelector('input[type=number]');

    input.oninput = function() {
        if (input.value.length == 4) {
            input.form.submit();
        }
    };
</script>