How to find out what character key is pressed?

How to find out what character key is pressed?

I would like to find out what character key is pressed in a cross-browser compatible way in pure javascript.

Solutions/Answers:

Solution 1:

“Clear” JavaScript:

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

JQuery:

$(document).keypress(function(event){
  alert(String.fromCharCode(event.which)); 
});

Solution 2:

There are a million duplicates of this question on here, but here goes again anyway:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    var charStr = String.fromCharCode(charCode);
    alert(charStr);
};

The best reference on key events I’ve seen is http://unixpapa.com/js/key.html.

Solution 3:

More recent and much cleaner: use event.key. No more arbitrary number codes!

node.addEventListener('keydown', function(event) {
    const key = event.key; // "a", "1", "Shift", etc.
});

If you want to make sure only single characters are entered, check key.length === 1, or that it is one of the characters you expect.

Mozilla Docs

Supported Browsers

Solution 4:

Have a look at this site for cross browser inconsistencies
http://www.quirksmode.org/js/keys.html

Solution 5:

Use this one:

function onKeyPress(evt){
  evt = (evt) ? evt : (window.event) ? event : null;
  if (evt)
  {
    var charCode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
    if (charCode == 13) 
        alert('User pressed Enter');
  }
}

Solution 6:

**check this out** 
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(document).keypress(function(e)
        {

            var keynum;
            if(window.event)
            { // IE                 
                keynum = e.keyCode;
            }
                else if(e.which)
                    { 
                    // Netscape/Firefox/Opera                   
                    keynum = e.which;
                    }
                    alert(String.fromCharCode(keynum));
                    var unicode=e.keyCode? e.keyCode : e.charCode;
                    alert(unicode);
        });
});  

</script>
</head>
<body>

<input type="text"></input>
</body>
</html>