Home > Web Front-end > JS Tutorial > JavaScript onkeypress event entry example (press or hold a keyboard key)_Basic knowledge

JavaScript onkeypress event entry example (press or hold a keyboard key)_Basic knowledge

WBOY
Release: 2016-05-16 16:33:47
Original
1922 people have browsed it

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:

Copy code The code is as follows:



<script><br> function checkNumber(e)<br> {<br> var keynum = window.event ? e.keyCode : e.which;<br> //alert(keynum);<br> var tip = document.getElementById("tip");<br> If( (48<=keynum && keynum<=57) || keynum == 8 ){<br />          tip.innerHTML = "";<br />         return true;<br /> }else {<br /> ​​​​ tip.innerHTML = "Tip: Only numbers can be entered!";<br />          return false;<br /> }<br /> } <br /> </script>



Please enter a number:




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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template