Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Text Input: Avoid submit when enter is pressed

Tags:

html

textbox

I have an HTML input which is a textfield. When I am pressing the enter, this will call the submit, which is normal.

Now, I would like to do something else when Enter is clicked on that textBox.

I am trying something like that:

<input type="text"         id="first_page"          onPaste=""         onkeydown="if (event.keyCode == 13) alert('enter')" /> 

The alert works well but the submit is still done. My page is reloading after that.

Could you help me please.

like image 421
Milos Cuculovic Avatar asked Sep 05 '12 09:09

Milos Cuculovic


People also ask

How do you avoid form submit on Enter?

Use preventDefault() event method to Prevent form submission on the “Enter” key pressed in JavaScript. Enter key keycode is 13, so you can check in if statement.

How do I stop enter key press to submit a web form?

In a simplest way: $("#myinput"). keydown(function (e) { if(e. which == 13) e. preventDefault(); }); The key is to use "keydown" and event.

How do I stop a form from submitting in HTML?

The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.

How Prevent form submit on enter key press jQuery?

getElementById("testForm"); form. addEventListener("submit",function(e){e. preventDefault(); return false;}); This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.


2 Answers

write return false; and check it

like image 124
Hkachhia Avatar answered Nov 06 '22 03:11

Hkachhia


Using jquery

<script>             $('#first_page').keypress(function(e) {               if (e.keyCode == '13') {                  e.preventDefault();                  //your code here                }             });​         </script> 

using javascript

<input type="text" id="first_page"  onPaste="" onkeydown="if (event.keyCode == 13) { alert('enter');return false;}" /> 
like image 27
Sibu Avatar answered Nov 06 '22 01:11

Sibu