最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript capture key - Stack Overflow

programmeradmin4浏览0评论

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 ing 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.

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 ing 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.

Share Improve this question asked Apr 16, 2009 at 15:53 Alec SmartAlec Smart 95.9k39 gold badges124 silver badges186 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

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
  }
}

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

Even if you block the enter button, they could still paste in newlines. This would prevent the enter button, and remove any newlines and carriage returns that got in anyway (only tried this on FF, and minimal thought put into this - it might not work on Safari or IE as-is).

<textarea rows="20" cols="50" onkeydown="return ignoreEnter(event);" onkeyup="noEnter(this);"></textarea>
<script type="text/javascript">
function ignoreEnter( event ) {
 return thisEvent.keyCode != 13; // enter key
}

function noEnter( e ) {
 e.value = e.value.replace(/\n/g,'');
 e.value = e.value.replace(/\r/g,'');
}
</script>
发布评论

评论列表(0)

  1. 暂无评论