Javascript DOM KeyboardEvent keyCode Property get character code and key code

Introduction

The 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) {/*from   w w w.j  a  va2 s. c  om*/
  var char = event.which || event.keyCode;
  document.getElementById("demo").innerHTML = "The Unicode CHARACTER code is: " + char;
}

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

</body>
</html>



PreviousNext

Related