如何防止在基于web的应用程序中按ENTER键提交表单?
当前回答
你会发现这更简单和有用:D
$(document).on('submit', 'form', function(e){
/* on form submit find the trigger */
if( $(e.delegateTarget.activeElement).not('input, textarea').length == 0 ){
/* if the trigger is not between selectors list, return super false */
e.preventDefault();
return false;
}
});
其他回答
如何:
<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,当你在其中点击返回时,将没有正确的名称。
[2012修订版,没有内联处理程序,保留textarea进入处理]
function checkEnter(e){
e = e || event;
var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}
现在你可以在表单上定义一个按键处理程序: <形式[…onkeypress="return checkEnter(event)">
document.querySelector('form').onkeypress = checkEnter;
在过去,我总是用类似上面的按键处理程序来完成它,但今天遇到了一个更简单的解决方案。输入键只是触发表单上第一个未禁用的提交按钮,所以实际上所需要的只是拦截试图提交的按钮:
<form>
<div style="display: none;">
<input type="submit" name="prevent-enter-submit" onclick="return false;">
</div>
<!-- rest of your form markup -->
</form>
就是这样。按键将像往常一样由浏览器/字段等处理。如果进入-提交逻辑被触发,那么浏览器将找到隐藏的提交按钮并触发它。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.
你将不得不调用这个函数,它将取消表单的默认提交行为。您可以将它附加到任何输入字段或事件。
function doNothing() {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if( keyCode == 13 ) {
if(!e) var e = window.event;
e.cancelBubble = true;
e.returnValue = false;
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}