This article mainly introduces the JavaScriptonkeypress event entry instance, where the onkeypress event captures the situation of pressing or holding a keyboard button. For more information, see
JavaScript onkeypress event
The onkeypress event is triggered when you press or press a keyboard button.
Note: The onkeypress event is slightly different from the onkeydown event. The onkeypress event is not processed by pressing the corresponding function key. You can change the following example to an onkeydown event! @ # $ And other special characters can tell the difference between the two.
Prompt
Internet Explorer/Chrome uses event. keyCode to retrieve the characters that have been pressed, whereas Netscape/Firefox/Opera and other browsers use event. which.
The onkeypress event allows only numbers.
The following is an example of using the onkeypress event to allow users to enter numbers only in the form field:
The Code is as follows:
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 numbers can be entered! ";
Return false;
}
}
Script
Enter a number:
Event. keyCode/event. which obtains the numeric value (Unicode encoding) corresponding to a key. common key values are listed in the onkeydown event section. In this example, the value of 8 is specially processed to support the Backspace key in the text domain.