简体   繁体   中英

How to detect input-text pressed key on javascript

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

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM