Copy codeThe Code is as follows:
<Html>
<Body>
<Textarea id = "t"> </textarea>
<Input type = "text" id = "b2"/>
<Script type = "text/javascript">
TextAreaLimit ("t", {lastMsgLabel: "b2 "})
Function textAreaLimit (area, op ){
Var defaultOp = {
MaxLength: 10 // maximum length
, IsNumber: false // only numbers are allowed
, LastMsgLabel: null // instantly displays the number of inputs
, Msg: "{0} characters can also be entered"
, ErrorMsg: "The maximum number of characters has been exceeded"
};
Var label;
If (typeof area = "string "){
Area = document. getElementById (area );
}
If (! Area ){
Return;
}
For (var I in op ){
DefaultOp [I] = op [I];
}
If (defaultOp. lastMsgLabel ){
If (typeof defaultOp. lastMsgLabel = "string "){
Label = document. getElementById (defaultOp. lastMsgLabel );
}
}
If (defaultOp. IsNumber ){
Area. style. imeMode = "Disabled"; // IE
Area. onkeydown = function (){
Return event. keyCode! = 229;
}
}
Area. onkeyup = function (){
If (defaultOp. IsNumber ){
This. value = this. value. replace (// \ D/g, ""); // outside of IE
}
If (this. value. length> defaultOp. maxLength ){
//-------------------------------------------------------------------------------
// Solution ①
This. disabled = "disabled ";
This. value = this. value. slice (0, defaultOp. maxLength );
This. removeAttribute ("disabled ");
This. focus ();
// Solution ②
// Or
// Alert (defaultOp. errorMsg );
// This. value = this. value. slice (0, defaultOp. maxLength );
//-------------------------------------------------------------------------------
}
If (label ){
Label. value = defaultOp. msg. replace (/\ {0 \}/, defaultOp. maxLength-this. value. length );
}
}
}
</Script>
</Body>
</Html>
The BUG that occurs when entering Japanese + fullwidth is mainly the code in the middle of the red line.
The idea is to interrupt the input status of Japanese.
If the input exceeds the limit, use solution ②. Otherwise, use solution ①.