JavaScript onkeypress Events
The onkeypress event is triggered when the user presses or holds a keyboard key.
Note: There are some slight differences between the onkeypress event and the onkeydown event. The onkeypress event does not handle the corresponding function key pressing. For specific examples, you can change the following example to the onkeydown event, and enter special characters such as !@#$ to understand the difference.
hint
Internet Explorer/Chrome browser uses event.keyCode to retrieve the pressed characters, while browsers such as Netscape/Firefox/Opera use event.which.
Only numbers are allowed to be entered using the onkeypress event
Here is an example of using the onkeypress event that allows users to enter numbers only in the form field:
The code copy is as follows:
<html>
<head>
<script>
function checkNumber(e)
{
var keynum = window.event ? e.keyCode : e.which;
//alert(keynum);
var tip = document.getElementById("tip");
if( (48<=keynum && keynum<=57) || keynum == 8 ){
tip.innerHTML = "";
return true;
}else {
tip.innerHTML = "Tip: Only enter numbers!";
return false;
}
}
</script>
</head>
<body>
<div>Please enter the number: <input type="text" onkeypress="return checkNumber(event);" />
<span id="tip"></span>
</div>
</body>
</html>
event.keyCode/event.which gets the numeric value corresponding to a key (Unicode encoding), and the commonly used 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.