I have an html form with some input fields in it, one of the input field is search field, when I click the search button next to this search input field, search results will be returned from server using ajax, what I want is to prevent form submission when user focuses on this specific search input field and hit enter. By the way, I'm using AngularJS, so solution might be a bit different from JQuery or pure javascript way I think.. Do-able? Any advice would be appreciated!
Asked
Active
Viewed 1.0k times
3 Answers
3
Use a function like:
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>

Ian Hazzard
- 7,661
- 7
- 34
- 60
-
yup, for angularJS, all I need to do is to change onKeyDown to ng-keydown, right on! Thank you! – dulan Oct 21 '14 at 03:31
2
In the button click handler do a e.preventDefault()
function clickHandler(e){
e.preventDefault();
}
You can also use a button
instead of a submit button.

TGH
- 38,769
- 12
- 102
- 135
-
Doesn't this prevent all submissions? Is it possible to only prevent form submission when user focuses on this input field and not the others? By the way, I'm using angularJS, where should I put this code in? – dulan Oct 21 '14 at 03:15
-
-
-
If you're doing this you might as well do `ng-click="doStuff(); $event.stopPropagation()"` – Pylinux Jan 13 '16 at 22:57
-
@Pylinux How would I go about overridding the default behavior 'for submission' to call a function instead? – crazyCoder Feb 24 '17 at 07:08
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;

Vineet Jain
- 21
- 1