我有一个带有输入字段的html表单,其中一个输入字段是搜索字段,当我点击此搜索输入字段旁边的搜索按钮时,将使用ajax从服务器返回搜索结果,我想要的是什么是当用户关注此特定搜索输入字段并按Enter键时阻止表单提交。顺便说一句,我正在使用AngularJS,因此解决方案可能与JQuery或纯JavaScript方式有点不同我认为..可行吗?任何建议将不胜感激!
答案 0 :(得分:3)
使用如下函数:
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();
}
}

<form name="input" action="http://www.google.com" method="get">
<input type="text" onkeydown="doNothing()">
<br><br>
<input type="submit" value="Submit">
</form>
&#13;
答案 1 :(得分:2)
在按钮点击处理程序中执行e.preventDefault()
function clickHandler(e){
e.preventDefault();
}
您也可以使用button
代替提交按钮。
答案 2 :(得分:0)
When you submit form using enter key on particular text fields or submit button(focus).
To prevent form submit twice, we can use both approach
1.
define var isEnterHitOnce=true globally which loaded at the time of form load
on keyPress Event or on submitForm()
if(event.keycode==13 && isEnterHitOnce){
isEnterHitOnce=false;
//Process your code. Sent request to server like submitForm();
}
isEnterHitOnce=false;
2.
disable the field object from where you received the action like
beginning of method in formSubmit()
document.getElementById(objName).disabled=true; // objName would be your fields name like submitButton or userName
//At the end of method or execution completed enable the field
document.getElementById(objName).disabled=false;