我在一个网站上有一个调查,用户按下回车键(我不知道为什么),不小心没有点击提交按钮就提交了调查(表单),这似乎有些问题。有办法防止这种情况吗?
我在调查中使用HTML, PHP 5.2.9和jQuery。
我在一个网站上有一个调查,用户按下回车键(我不知道为什么),不小心没有点击提交按钮就提交了调查(表单),这似乎有些问题。有办法防止这种情况吗?
我在调查中使用HTML, PHP 5.2.9和jQuery。
当前回答
一种完全不同的方法:
The first <button type="submit"> in the form will be activated on pressing Enter. This is true even if the button is hidden with style="display:none; The script for that button can return false, which aborts the submission process. You can still have another <button type=submit> to submit the form. Just return true to cascade the submission. Pressing Enter while the real submit button is focussed will activate the real submit button. Pressing Enter inside <textarea> or other form controls will behave as normal. Pressing Enter inside <input> form controls will trigger the first <button type=submit>, which returns false, and thus nothing happens.
因此:
<form action="...">
<!-- insert this next line immediately after the <form> opening tag -->
<button type=submit onclick="return false;" style="display:none;"></button>
<!-- everything else follows as normal -->
<!-- ... -->
<button type=submit>Submit</button>
</form>
其他回答
这将禁用页面上所有表单的输入键,并且不阻止在文本区域输入。
// disable form submit with enter
$('form input:not([type="submit"])').keydown((e) => {
if (e.keyCode === 13) {
e.preventDefault();
return false;
}
return true;
});
我需要防止只提交特定的输入,所以我使用了一个类选择器,让它成为我需要的“全局”特性。
<input id="txtEmail" name="txtEmail" class="idNoEnter" .... />
jQuery代码:
$('.idNoEnter').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
或者,如果keydown不够用:
$('.idNoEnter').on('keypress keydown keyup', function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
一些注意事项:
在这里修改各种不错的答案,Enter键似乎适用于所有浏览器的keydown。对于替代方法,我将bind()更新为on()方法。
我是类选择器的忠实粉丝,权衡所有的利弊和性能讨论。我的命名约定是'idSomething',表示jQuery将其用作id,以将其与CSS样式分开。
不需要阻止用户按Enter键(这似乎不自然),您可以让表单保持原样,并添加一些额外的客户端验证:当调查未完成时,结果不会发送到服务器,用户会收到一条漂亮的消息,告诉需要完成哪些内容才能完成表单。如果您正在使用jQuery,请尝试验证插件:
http://docs.jquery.com/Plugins/Validation
这将需要比捕捉Enter按钮更多的工作,但肯定会提供更丰富的用户体验。
这里已经有很多好的答案,我只是想从用户体验的角度贡献一些东西。键盘控件在表单中非常重要。
问题是如何在按回车键时禁用提交。而不是如何在整个应用程序中忽略Enter。因此,考虑将处理程序附加到表单元素,而不是窗口。
禁用Enter表单提交仍然允许以下:
当提交按钮被聚焦时,通过输入提交表单。 填充所有字段时提交表单。 通过Enter与非提交按钮交互。
这只是一个样板,但它符合所有三个条件。
$(“形式”)。On ('keypress',函数(e) { //注册按键。 $attr = $(e.target).attr('type'); $node = e.target.nodeName.toLowerCase(); if ($ attr = = =“按钮”| | $ attr = = = '提交' | | $ node = = =“文本区域”){ 返回true; } //如果没有填充所有字段,则忽略按键。 if (e.which === 13 && ! fieldsarepopulate (this)) { 返回错误; } });
没有提交按钮也行。只需在输入(type=button)中放入一个脚本,如果希望它提交表单中的数据,则添加eventListener。
而是使用这个
<input type="button" onclick="event.preventDefault();this.closest('form').submit();">
而不是用这个
<input type="submit">
注意:这里需要onclick在点击时实际提交表单。默认情况下,type="button"不足以提交。