JavaScript onkeypress Event Entry instance (press or hold a keyboard key) _ Basics

Source: Internet
Author: User
Tags numeric value

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.