How to detect input-text pressed key on javascript

拈花ヽ惹草 提交于 2019-12-12 03:43:28

问题


I have this simple document:

   <!DOCTYPE html>
      <html>
        <body>
        <input id="mytext" onkeypress="myfun(e)"></input>
        <p id="demo"></p>
        <script> function myfun(e){ 
                if(e.keyCode==13) alert('Enter Key Pressed');}
        });
        </script>
        </body>
      </html>

what I want is: when user press enter key on mytext, show an alert to inform the user like this message : Enter Key Pressed

I did every thing like above, But it doesn't work and no any alert is shown when enter pressed on mytext.

Help Please!..


回答1:


Your code works when you replace myfun(e) with myfun(event). I also corrected some syntactical errors.

 <html>
    <body>
        <input id="mytext" onkeypress="myfun(event)"></input>
        <p id="demo"></p>
        <script> 
            function myfun(e){ 
                    if(e.keyCode==13) alert('Enter Key Pressed');
            };
        </script>
    </body>
</html>



回答2:


You can add an event listener to listen for the onkeypress event:

document.getElementById('mytext').addEventListener('keypress', function(e) {
    if(e.keyCode == 13) alert('Enter Key Pressed');
});

Also, input tag's don't have a closing tag. Here's a live example

If you want to call it inline as a handler, try this:

<input id="mytext" onkeypress="myfun(event)">
<p id="demo"></p>
<script>
function myfun(event){ 
    var key = event.keyCode || event.which;
    if(key === 13) alert('Enter Key Pressed');
}
</script>

You must use event as a parameter to make sure it works correctly as a handler. Now, get's the key code and check if it's 13, then alerts.



来源:https://stackoverflow.com/questions/39302973/how-to-detect-input-text-pressed-key-on-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!