Home >Web Front-end >JS Tutorial >JavaScript onkeypress event entry example (press or hold a keyboard key)_Basic knowledge
JavaScript onkeypress event
The onkeypress event is triggered when the user presses or holds down a keyboard key.
Note: The onkeypress event is slightly different from the onkeydown event. The onkeypress event does not process the corresponding function key press. Specifically, you can change the following example to the onkeydown event, and you can enter special characters such as !@#$ to feel the difference between the two.
Tips
Internet Explorer/Chrome browsers use event.keyCode to retrieve the pressed character, while browsers such as Netscape/Firefox/Opera use event.which.
Use the onkeypress event to only allow numbers to be entered
The following is an example of using the onkeypress event to only allow users to enter numbers in a form field:
event.keyCode/event.which gets the numeric value (Unicode encoding) corresponding to a key. Common key values are listed in the onkeydown event section. In the example, the value of 8 is specially processed to support the Backspace key in the text field.