Search code examples
javascriptdom-eventsonkeypress

How to know pressed key using Javascript?


Possible Duplicate:
js: how to find out what character key is pressed?

I want to know how to make an event on key pressing and to specify which key is pressed using Javascript only.


Solution

  • <script type="text/javascript">
        function myKeyPress(e){
    
            var keynum;
    
            if(window.event){ // IE                 
                keynum = e.keyCode;
            }else
                if(e.which){ // Netscape/Firefox/Opera                  
                    keynum = e.which;
                 }
            alert(String.fromCharCode(keynum));
        }
       </script>
    
    
     <form>
      <input type="text" onkeypress="return myKeyPress(event)" />
     </form>
    

    Referred from How to find out what character key is pressed?