31

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
  • 39,551
  • 56
  • 175
  • 291
Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265

9 Answers9

27

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;}" />
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Sibu
  • 4,609
  • 2
  • 26
  • 38
26

write return false; and check it

Hkachhia
  • 4,463
  • 6
  • 41
  • 76
  • 10
    This is now marked as deprecated. Should now be event.preventDefault() and/or event.stopPropagation() – thsorens Jun 15 '15 at 11:46
7

Other option would be using onkeypress

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

You could try the below script :

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

And the Html:

<input type="text" id="first_page" onPaste="" onkeydown="return checkEnter(event);" />
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 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,550
  • 11
  • 97
  • 161
1

write the following code after alert('enter')

return false;
Hkachhia
  • 4,463
  • 6
  • 41
  • 76
Tarun Tak
  • 411
  • 1
  • 7
  • 17
1

Use this, it worked in mine.

Replace on the keydown:

onkeydown="if (event.keyCode == 13 || event.which == 13) event.preventDefault();"
Abdul Afiq
  • 11
  • 3
-1
 $(function () {$('#form').validationEngine(); });

It will work in my mvc problem

Hkachhia
  • 4,463
  • 6
  • 41
  • 76
laki laki
  • 39
  • 2
-3

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