javascript 输入时提交表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8955155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submit form on enter
提问by Blainer
How do I make this submit on pressing the enter key? I want to completely remove the submit button.
如何在按下回车键时提交?我想完全删除提交按钮。
HTML
HTML
<form class="iform">
<input id='input1' name='input1'/>
<input type='button' value='GO!' id='submit' onclick='onSubmit()' />
</form>
JS
JS
$('#submit').click(function() {
$('#slider').anythingSlider($("#input1").val());
});
回答by Wesley Murch
Hitting "enter" while focused in the text field will already submit the form, you don't actually needthe submit button (look at Stack Overflow's "search" form at the top right of this page for example). You just might need to change your javascript to listen to the submit
event instead:
在文本字段中点击“输入”将已经提交表单,您实际上并不需要提交按钮(例如,查看此页面右上角的 Stack Overflow 的“搜索”表单)。您可能只需要更改您的 javascript 来监听submit
事件:
$('form').submit(function() {
$('#slider').anythingSlider($("#input1").val());
});
If you want the form submitted when someone presses enter regardless of where the focus is, I would suggest against it. It's extremely confusing behavior and can easily be triggered by accident.
如果你想在有人按下回车键时提交表单而不管焦点在哪里,我建议不要这样做。这是非常令人困惑的行为,很容易被意外触发。
回答by mplungjan
Very simple since you have only one field
非常简单,因为您只有一个字段
EITHER
任何一个
<form class="iform" id="iform">
<input id='input1' name='input1'/>
<input type='submit' value='GO!' />
</form>
OR even
甚至
<form class="iform" id="iform">
<input id='input1' name='input1'/>
</form>
JS in either case
JS 在任何一种情况下
$('#iform').submit(function(e) {
$('#slider').anythingSlider($("#input1").val());
e.preventDefault();
});
回答by Jorge Zapata
Try this:
试试这个:
$('#formId').keypress(function(e){
if(e.which == 13)
$('#slider').anythingSlider($("#input1").val()); }
return false;
});
回答by pensan
a normal form is automatically submitted when pressing enter.
按回车键时会自动提交普通表单。
<form id="form1" action="test.php">
<input type="text" name="input1" />
</form>
this should work fine, but it may not validate.
这应该可以正常工作,但可能无法验证。
If you want to submit your form in javascript, you can use the .submit() function.
如果你想在 javascript 中提交你的表单,你可以使用 .submit() 函数。
document.forms["form1"].submit();
or jQuery
或 jQuery
$("#form1").submit();
回答by Dau
use this
用这个
<input type="submit" style="display:none;">
回答by damoiser
A simpler solution without the submit button:
没有提交按钮的更简单的解决方案:
HTML
HTML
<form action="path_to_the_action">
<input class="submit_on_enter" type="text" name="q" placeholder="Search...">
</form>
jQuery
jQuery
<script type="text/javascript">
$(document).ready(function() {
$('.submit_on_enter').keydown(function(event) {
if (event.keyCode == 13) {
this.form.submit();
return false;
}
});
});
</script>