Introduction to OnKeyUp and onkeydown in JavaScript basics

Source: Internet
Author: User

Yesterday in writing the last dynamic generation of the box and text box to limit the input encountered a problem, the text box entered the time to start to calculate the text box input How many words, naturally thought of the onkeydown event, and then calculate the Value.length method, see the code

Copy Code code as follows:

Moto.onkeydown=function () {
var curlen=+this.value.length;
Shuru.innerhtml=curlen;
shuru2.innerhtml=+ (200-curlen);
if (curlen>=200) {
This.value=this.value.substring (0,200);
curlen=200;
shuru.innerhtml=200;
shuru2.innerhtml=0;
return false;
}
}

The results found that the text input after the word count is not correct, is originally 4 words after the input to find the word or show 0

Thought for a long time, finally when the bar onkeydown replaced onkeyup, everything will be fine

There's a difference between the two events.
The onkeydown is triggered when pressed, and the key value is not lost. The onkeyup is performed when the button is raised, and the key value is already there. And how long does it matter, like you add these 2 events to the input box,
Copy Code code as follows:

<input type= "text" id= "test1" onkeydown= "alert (this.value);" />
<input type= "text" id= "test2" onkeyup= "alert (this.value);" />

Take a look at these two different running results to understand!
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>insert title here</title>
<body>
<input type= "text" id= "test1" onkeydown= "alert (this.value);" />
<input type= "text" id= "test2" onkeyup= "alert (this.value);" />
</body>

The onkeydown is triggered when pressed, and the key value is not lost.
The onkeyup is performed when the button is raised, and the key value is already there.
And how long does it matter, like you add these 2 events to the input box,

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.