13

I have a form with a textfield inside and I am trying to disable the default behavior when the browser submits the whole form if the user presses Enter while the textfield is selected.

$('#recaptcha_response_field').keydown(function(event) { if (event.keyCode == 13) { event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); alert("You Press ENTER key"); return false; } }); 

Currently am getting "You Press ENTER key" and the default behavior isn't overridden.

11
  • 1
    Don't use keydown event of input, use submit event of form. Commented Apr 17, 2013 at 14:19
  • You should also handle keyup event. Commented Apr 17, 2013 at 14:20
  • 1
    Duplicate stackoverflow.com/questions/585396/… Pls ask your question to google before submitting it here. this would have provided you with the original question that has already been answered at length. Commented Apr 17, 2013 at 14:21
  • 1
    preventDefault is absolutely enough. Neither do you need to stop propagation, nor return false. Commented Apr 17, 2013 at 14:22
  • See this post bloggingdeveloper.com/post/… Commented Apr 17, 2013 at 14:22

5 Answers 5

25

Try this:

$(document).on("keypress", 'form', function (e) { var code = e.keyCode || e.which; if (code == 13) { e.preventDefault(); return false; } }); 

This will prevent the form submit on keypress

DEMO HERE

Sign up to request clarification or add additional context in comments.

3 Comments

keyup fires after the submit and therefore, you cannot disable default behavior since it has already happened.
Also stops textareas from pressing enter for new lines \n
keydown fires first so it is safest to use.
13

I found this and it works for me.

<input type="text" name="somename" id="someid" value="" onkeypress="return event.keyCode!=13"> 

Comments

9

To prevent the script from blocking the enter key on other elements such as on a textarea. Change the target from "form" to "input".

$(document).on("keypress", "input", function (e) { var code = e.keyCode || e.which; if (code == 13) { e.preventDefault(); return false; } });

1 Comment

thanks, man, only one what truly helped for my case
3

If none of the above solution is working for you , and you are using javascript anyway , why don't you use button type as 'button' <input type='button'> and submit it using javascript

$('#form_id').submit(); 

Comments

1

U can use this script to prevent enter on entire from.

<script type="text/javascript"> $(document).on("keypress", 'form', function (e) { if (e.target.className.indexOf("allowEnter") == -1) { var code = e.keyCode || e.which; if (code == 13) { e.preventDefault(); return false; } } }); </script> 

you put the classname to which control need to use enter

1 Comment

probably will not work on Mac as Mac has different keycodes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.