48

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();
   }
});
Brian Webster
  • 30,033
  • 48
  • 152
  • 225
James T
  • 3,292
  • 8
  • 40
  • 70
  • I dont think the event is triggering, how can I tell if `$('#comment')` is correctly being what I want? – James T Jan 20 '11 at 23:30
  • 1
    Rememebr to hook into the change event as well as the keyup/down/press that everybody else has displayed. with every solution here, people can still paste linebreaks into th textarea, to prevent that you need to remove them ;) – Martin Jespersen Jan 20 '11 at 23:45

6 Answers6

93

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();
    }
});
Semmel
  • 2,526
  • 3
  • 21
  • 30
kajo
  • 5,631
  • 4
  • 31
  • 29
16

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:

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.

gilly3
  • 87,962
  • 25
  • 144
  • 176
8

Use event.keyCode in the keydown event:

$('#comment').keydown(function(event) {
   if(event.keyCode == 13) return false;
   //carry on...
});
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
3
$('#comment').keypress(function(event) {
    if (event.keyCode == 13) {
        event.preventDefault();
    }
});
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
3

While the answers provided here will prevent someone from typing a carriage return, it will not prevent someone from pasting one in.

You would need to do some post processing of the text (in javascript or server-side) to remove them.

http://jsfiddle.net/we8Gm/

But the question is, why? Why not simply use <input type="text"></input> which takes care of this automatically as it is a single-line input element?

Jeff B
  • 29,943
  • 7
  • 61
  • 90
2

Try with .keypress and use return false;

Good luck!

Gonzalo Larralde
  • 3,523
  • 25
  • 30