Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript capture key

Tags:

javascript

I am trying to catpure the enter key from a textarea using javascript. The problem is that although I am able to find out that the "enter" key was pressed, I am not unable to avoid it from coming in the textarea. I dont want the enter key i.e. "\n" to be displayed in the text area.

Any suggestions on how to achieve that?

Thank you.

like image 857
Alec Smart Avatar asked Apr 16 '09 15:04

Alec Smart


2 Answers

Try setting this function as the onKeyDown event for the text area:

ex: onkeydown="javascript:return fnIgnoreEnter(event);"

function fnIgnoreEnter(thisEvent) {
  if (thisEvent.keyCode == 13) { // enter key
    return false; // do nothing
  }
}
like image 179
wweicker Avatar answered Oct 18 '22 22:10

wweicker


More recent and much cleaner: use event.key instead of event.keyCode. No more arbitrary number codes!

function onEvent(event) {
    if (event.key === "Enter") {
        return false;
    }
};

Mozilla Docs

Supported Browsers

like image 30
Gibolt Avatar answered Oct 18 '22 23:10

Gibolt