当您在输入中填写了 4 个数字时,我想自动提交表格。我目前只有一个基本的 html 表单:
<form action="send.php" method="POST">
<input type="number" maxlength="4">
</form>
现在我希望,如果您达到最大长度,它会自动提交表单,因此您不必按回车键或提交。有什么办法可以做到这一点吗?
试试这个 - 使用键触发的 frunction 并使用 jQuery - 也获取函数中的 maxlength,因为它将来可能会更改。我还在那里添加了一条警报,以便您可以在代码片段中看到效果 - 仅用于 SO。
//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();}
})
<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>
你可以
这样做:
- 将键控侦听器添加到输入
- 检查其中值的长度
function checkField(input) {
if(input.value.length == 4) {
document.forms[0].submit();
}
}
<form action="send.php" method="POST">
<input type="number" onkeyup="checkField(this)"/>
</form>
您可以定义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>