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>