Javascript capture key

前端 未结 3 1934
情深已故
情深已故 2020-12-03 19:31

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

相关标签:
3条回答
  • 2020-12-03 20:11

    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
      }
    }
    
    0 讨论(0)
  • 2020-12-03 20:13

    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 讨论(0)
  • 2020-12-03 20:20

    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

    0 讨论(0)
提交回复
热议问题