Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html form prevent submit when hit enter on specific input [duplicate]

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!

like image 622
dulan Avatar asked Oct 21 '14 03:10

dulan


2 Answers

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> 

JSFIDDLE HERE

like image 196
Drazzah Avatar answered Sep 28 '22 07:09

Drazzah


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.

like image 29
TGH Avatar answered Sep 28 '22 08:09

TGH