如何防止在基于web的应用程序中按ENTER键提交表单?
当前回答
如何:
<script>
function isok(e) {
var name = e.explicitOriginalTarget.name;
if (name == "button") {
return true
}
return false;
}
</script>
<form onsubmit="return isok(event);">
<input type="text" name="serial"/>
<input type="submit" name="button" value="Create Thing"/>
</form>
只要给你的按钮命名,它仍然会提交,但文本字段,即显式originaltarget,当你在其中点击返回时,将没有正确的名称。
其他回答
ENTER键仅仅激活表单的默认提交按钮,这将是第一个
<input type="submit" />
浏览器在表单中查找。
所以不要有提交按钮,而是类似的东西
<input type="button" value="Submit" onclick="submitform()" />
编辑:回应评论中的讨论:
如果只有一个文本字段,这就行不通了——但在这种情况下,这可能是理想的行为。
另一个问题是,这依赖于Javascript来提交表单。从可访问性的角度来看,这可能是一个问题。这可以通过用javascript编写<input type='button'/>来解决,然后在<noscript>标签中放入<input type='submit' />。这种方法的缺点是,对于禁用javascript的浏览器,您将在ENTER时提交表单。在这种情况下,由OP决定期望的行为是什么。
我知道没有办法做到这一点而不调用javascript。
I Have come across this myself because I have multiple submit buttons with different 'name' values, so that when submitted they do different things on the same php file. The enter / return button breaks this as those values aren't submitted. So I was thinking, does the enter / return button activate the first submit button in the form? That way you could have a 'vanilla' submit button that is either hidden or has a 'name' value that returns the executing php file back to the page with the form in it. Or else a default (hidden) 'name' value that the keypress activates, and the submit buttons overwrite with their own 'name' values. Just a thought.
请查看这篇文章如何防止按ENTER键提交web表单?
$(“.pc_prevent_submit”)时函数(){ 美元(窗口).keydown(函数(事件){ 如果事件。keyCode == 13) { event.preventDefault (); 返回错误; } }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <form class= " pc_prevent_submit " action= " " method= " post " > <input type= " text " name= " username " > <input type= " password " name= " userpassword " > <input type= " submit " value= " submit " > > < /形式
以下是我的做法:
window.addEventListener('keydown', function(event)
{
if (event.key === "Enter" && event.target.tagName !== 'TEXTAREA')
{
if(event.target.type !== 'submit')
{
event.preventDefault();
return false;
}
}
});
我在这里或其他帖子中找到的所有关于这个主题的答案都有一个缺点,那就是它阻止了表单元素上的实际更改触发器。所以如果你运行这些解决方案,onchange事件也不会被触发。为了克服这个问题,我修改了这些代码,并为自己开发了以下代码。我希望这对其他人有用。 我给了一个类我的表单“prevent_auto_submit”,并添加以下JavaScript:
$(document).ready(function()
{
$('form.prevent_auto_submit input,form.prevent_auto_submit select').keypress(function(event)
{
if (event.keyCode == 13)
{
event.preventDefault();
$(this).trigger("change");
}
});
});