JavaScript onkeypress Events
The onkeypress event is triggered when the user presses or holds a keyboard key.
Note: onkeypress Events and onkeydown events are slightly different, onkeypress events do not do the corresponding function key pressed processing. The following example can be changed to the onkeydown event, you can enter special characters such as!@#$ to realize the difference between the two.
Tips
Internet explorer/chrome Browsers use Event.keycode to retrieve the pressed characters, while browsers such as Netscape/firefox/opera use Event.which.
Allow only numbers to be entered using the onkeypress Event
Here is an example of using the OnKeyPress event to allow users to enter numbers in form fields only:
Copy Code code as follows:
<script>
Function Checknumbe R (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 = "Hint: Only numbers can be entered!" ";
return false;
}
}
</script>
<body>
<div> Please enter a number: <input type = "text" onkeypress= "return CheckNumber (event);"/>
<span id= "Tip" ></SPAN>
</div>
</body>
</Html>
Event.keycode/event.which gets the numeric value of a key (Unicode encoding), and the common key values are listed in the OnKeyDown Event section. In the example, the value of 8 is specially processed in order to support the BACKSPACE (Backspace) key in the Text field.