Javascript DOM KeyboardEvent which Property get character code and key code

Introduction

Press any key on the keyboard in the input field to get the Unicode character code and the Unicode key code of the pressed key.

The which and keyCode property does not work on the onkeypress event for non-printable, function keys (like CAPS LOCK, CTRL, ESC, F12, etc.).

View in separate window

<!DOCTYPE html>
<html>
<body>
<input type="text" size="50" onkeypress="uniCharCode(event)" onkeydown="uniKeyCode(event)">
<p>onkeypress - <span id="demo"></span></p>
<p>onkeydown - <span id="demo2"></span></p>

<script>
function uniCharCode(event) {/*w  w  w.j a v a 2  s  .  co m*/
  var char = event.which || event.keyCode;
  document.getElementById("demo").innerHTML = "The Unicode CHARACTER code is: " + char;
}

function uniKeyCode(event) {
  var key = event.which || event.keyCode;
  document.getElementById("demo2").innerHTML = "The Unicode KEY code is: " + key;
}
</script>

</body>
</html>



PreviousNext

Related