JS TextArea string length restriction code set

Source: Internet
Author: User

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 ①.

Related Article

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.