Onkeypress is invalid for Chinese

Source: Internet
Author: User

To limit the input length in Javascript today, use the following Code :
<HTML>
<Body>
<Input type = "textbox" onkeypress = "javascript: zlk (5);"/>
<SCRIPT type = "text/JavaScript">
Function zlk (lsize)
{
If (event. srcelement. value. truelen ()> lsize)
{// When the length exceeds, cancel the input
Event. keycode = 0;
}
}
String. Prototype. truelen = function ()
{
VaR I = 0;
For (var j = 0; j <this. length; j ++)
{
If (this. charcodeat (j)> 255)
I + = 2;
Else
I ++;
}
Return I;
}
</SCRIPT>
</Body>
</Html>
The result shows that it works well for numbers and English, but it does not work for Chinese. It does not trigger the onkeypress event. I thought it was an IE bug and later found another event onpropertychange to handle it. The Code was changed to the following:
<HTML>
<Body>
<Input type = "textbox" onpropertychange = "javascript: zlpc (5);"/>
<SCRIPT type = "text/JavaScript">
VaR lastvalue = "";
Function zlpc (lsize)
{
// Debugger;
If (event. propertyname = "value ")
If (event. srcelement. value. truelen ()> lsize)
{// When the length exceeds, cancel the input
// Event. returnvalue = false; // The method for canceling the event has no effect.
// You have to use the method to restore the original value.
Event. srcelement. value = lastvalue;
}
Else
Lastvalue = event. srcelement. value;
}

string. prototype. truelen = function ()
{< br> var I = 0;
for (VAR J = 0; j {< br> If (this. charcodeat (j)> 255)
I + = 2;
else
I ++;
}< br> return I;
}< br>

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.