开发者

jQuery: Prevent enter key [duplicate]

This question already has answers here: Prevent users from submitting a form by hitting Enter (36 answers) Closed 6 years ago.

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

$('#comment').keyup(开发者_JS百科function(event) {
  if (event.text.charCodeAt() == '10') {
     event.preventDefault();
   }
});


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();
    }
});


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.


Use event.keyCode in the keydown event:

$('#comment').keydown(function(event) {
   if(event.keyCode == 13) return false;
   //carry on...
});


$('#comment').keypress(function(event) {
    if (event.keyCode == 13) {
        event.preventDefault();
    }
});


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?


Try with .keypress and use return false;

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜