This section describes a self-written jQuery text box character restriction plug-in. As for how to write the plug-in, I will not talk about it more here. You can refer to the related introduction, the function of this plug-in can be used to limit the maximum length of input characters.
• Character truncation speed can be set
• Customizable text styles of prompt information (improved custom text content)
This plug-in calculates the length of English characters and Chinese characters.
To put it bluntly, the detailed plug-in code is provided here. The specific implementation details have been commented in the Code:
The Code is as follows:
; (Function ($ ){
$. Fn. extend ({
TextAreaCount: function (options ){
Var $ textArea = this;
Options = $. extend ({
Maxlength: 140, // defines a maximum input length variable, initialized to 500
Speed: 15, // define the speed variable for deleting characters
Msgstyle: "font-family: Arial; font-size: small; color: Gray; small; text-align: right; margin-top: 3px ;", // display style of prompt information
MsgNumStyle: "font-weight: bold; color: Gray; font-style: italic; font-size: larger;" // The remaining length style in the prompt message
}, Options );
Var $ msg = $ ("
");
// Dynamically load a prompt message container behind the text box
$ TextArea. after ($ msg );
// Add a keypress event to determine whether the current content can be entered.
$ TextArea. keypress (function (e ){
// 8 is the Backspace button and 46 is the Delete button
// If the input character length is 0 and the key value is not 8 or 46, no operation is performed.
If ($ textArea. val (). length> = options. maxlength & e. which! = '8' & e. which! = '46 '){
E. preventDefault ();
Return;
}
}). Keyup (function () {// Add a keyup event to calculate the remaining input words and display them
Var curlength = this. value. length;
$Msg.html ("" ).html ("You can also enter" + (options. maxlength-curlength) + "word ");
Var init = setInterval (function (){
// If the input content is greater than the set maximum length, the content is automatically intercepted at the set speed
If ($ textArea. val (). length> options. maxlength ){
$ TextArea. val ($ textArea. val (). substring (0, options. maxlength ));
$Msg.html ("" ).html ("You can also enter" + options. maxlength + "word ");
}
Else {
ClearInterval (init );
}
}, Options. speed );
}). Bind ("contextmenu", function (e) {// right-click prohibited to prevent text operations by mouse
Return false;
});
// Prompt message indicating the length of characters that can be entered when loading for the first time
$Msg.html ("" ).html ("You can also enter" + options. maxlength + "word ");
Return this;
}
});
}) (JQuery );
Copy and save the above Code to jquery. textareacounter. js.
Demo:
Now let's take a look at how to use the plug-in. The Code is as follows:
The Code is as follows: