29

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.

Uwe Keim
  • 38,279
  • 56
  • 171
  • 280
Milos Cuculovic
  • 18,933
  • 50
  • 154
  • 263

9 Answers9

26

write return false; and check it

Hkachhia
  • 4,275
  • 5
  • 38
  • 74
  • 10
    This is now marked as deprecated. Should now be event.preventDefault() and/or event.stopPropagation() – thsorens Jun 15 '15 at 11:46
24

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;}" />
Sibu
  • 4,536
  • 2
  • 24
  • 38
6

Other option would be using onkeypress

<input type="text" id="first_page"  onPaste="" onkeypress="if (event.keyCode == 13) {alert('enter'); return false;}" />
s_a
  • 163
  • 2
  • 4
2

You could try the below script :

 <script>
 function checkEnter(event)
{
    if (event.keyCode == 13) 
   {
       alert('enter')
       return false;
    }
}

And the Html:

<input type="text" id="first_page"  onPaste="" onkeydown="return checkEnter(event);" />
Sandeep Pathak
  • 10,258
  • 7
  • 42
  • 57
1

You should be returning false in the keydown event handler function in order to prevent further processing of the event.

Also, you might find the following question useful: Prevent Users from submitting form by hitting enter.

Community
  • 1
  • 1
Xavi López
  • 27,094
  • 11
  • 98
  • 153
1

write the following code after alert('enter')

return false;
Hkachhia
  • 4,275
  • 5
  • 38
  • 74
Tarun Tak
  • 411
  • 1
  • 6
  • 17
0

Use this, it worked in mine.

Replace on the keydown:

onkeydown="if (event.keyCode == 13 || event.which == 13) event.preventDefault();"
0
 $(function () {$('#form').validationEngine(); });

It will work in my mvc problem

Hkachhia
  • 4,275
  • 5
  • 38
  • 74
laki laki
  • 31
  • 2
-2

using jquery you can avoid all submiting or some element

$("#form").submit(function(e) {
    e.preventDefault();
});
  • This will prevent the form from being submitted at all, which I doubt is the intent of the OP. – tbm Mar 14 '17 at 17:25