How to find out what character key is pressed?
"Clear" 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));
}
<input type="text" onkeypress="return myKeyPress(event)" />
JQuery:
$("input").keypress(function(event){
alert(String.fromCharCode(event.which));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
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.
More recent and much cleaner: use event.key
. No more arbitrary number codes!
NOTE: The old properties (
.keyCode
and.which
) are Deprecated.
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