JavaScript onKeyPress keyCode | Get Unicode char code example

An onkeypress event executes JavaScript when a user presses a key. The keyCode property returns the Unicode char code of the key that pressed the onkeypress event.

It can use in many form

HTML:

<element onkeypress="myScript">

JavaScript:

object.onkeypress = function(){myScript};

JavaScript, using the addEventListener() method:

object.addEventListener("keypress", myScript);

Suggestion: If you only want to detect whether the user has pressed a key, use the onkeydown event instead, because it works for all key types.

JavaScript onKeyPress event keyCode example

HTML examples code.

Alert button onkeypress property

This example illustrates the use of the onkeypress event:

<!DOCTYPE html>
<html>
<body>

  <input onkeypress="alert('Hello')"/>
</body>
</html>

JavaScript creating object

<!DOCTYPE html>
<html>

<body>

  <input type="text" id="txtbox">

  <script>

    var input = document.getElementById('txtbox');

    input.keypress = function() {
      const key = event.key;
      alert(key);
      
    };
  </script>

</body>
</html>

addEventListener() method

<!DOCTYPE html>
<html>
<body>

  <input type="text" id="txtbox">

  <script>

    var input = document.getElementById('txtbox');
    
    input.addEventListener('keypress', function(event) {
      const key = event.key;
      alert(key);
    });
  </script>

</body>
</html>

Output:

JavaScript onKeyPress keyCode

Note: The onkeypress event is not fired for all key types in all browsers. For details, please see the table below. To get the pressed key, use the keyCode, charCode and which event properties.

Do comment if you have any doubts and suggestions on this JS event code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.