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,