Search code examples
javascriptkeypress

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


Solution

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