Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Prevent enter key [duplicate]

I am trying to prevent the enter key from being put into a textarea, but it doesn't seem to work.

$('#comment').keyup(function(event) {   if (event.text.charCodeAt() == '10') {      event.preventDefault();    } }); 
like image 647
James T Avatar asked Jan 20 '11 23:01

James T


People also ask

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.

What is e keyCode === 13?

key 13 keycode is for ENTER key.

How do you disable the Enter key of an input textbox?

Disabling enter key for the formaddEventListener('keypress', function (e) { if (e. keyCode === 13 || e. which === 13) { e. preventDefault(); return false; } });


2 Answers

I have written little demonstration on jsfiddle.net, where you can try this code

Everybody has right answer :)

$('#comment').keypress(function (event) {     if (event.keyCode === 10 || event.keyCode === 13) {         event.preventDefault();     } }); 
like image 194
kajo Avatar answered Sep 23 '22 15:09

kajo


You can't cancel a keyup event. You can cancel keydown and keypress events though. In the documentation, notice that under "Event Information", "Cancels" is "No" for keyup:

  • keyup
  • keydown
  • keypress

Using keydown allows you to cancel far more keys than keypress, but if you don't want to cancel until after the key has been lifted, keypress is what you want. Fortunately for you, the enter key is one of the cancellable keys for the keypress event.

like image 42
gilly3 Avatar answered Sep 22 '22 15:09

gilly3