JavaScript keyCode with example

keyCode

JavaScript key events provide properties called 'keyCode' and 'which' , which you can use to identify which key in keyboard has been pressed by the user. This can be useful in scenarios where you want to perform some action at client side when user interacts through keyboard.

Example using keyCode which detects the ENTER click

<html>
<head>
  <script type="text/javascript">
   function showText (event) {
    var inputKeyCode = (event.which) ? event.which : event.keyCode;
    if ( inputKeyCode == 13 ) {     // checks if the key pressed is "Enter"
      alert("You have just entered : " + document.getElementById("inputText").value);
    }
   }
  </script>
</head>
<body>
    <strong>Enter some text and press ENTER<strong><br>
    <input id="inputText" size="30" onkeydown="showText(event)"/>
</body>
</html>

OUTPUT ( try it here ! )

Click here to know the keyCode for each key ( list of codes ).

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

www.000webhost.com