To limit the length of input characters in textarea, for example, to limit 140 characters in Twitter, You can implement the following methods:
1.
<Textarea name = "A" Cols = "45" rows = "2" onkeydown = 'if
(This. value. Length >=20) {event. returnvalue = false} '> AAAA </textarea>
2. We can also write the judgment in the function. If the input length exceeds the display limit, the prompt is displayed as follows:
<Form name = "testform">
<Textarea name = "A" Cols = "45" rows = "2"> AAAA </textarea>
<Input type = "button" onclick = "checkvalid ()" value = "Submit">
</Form>
<Script language = "JavaScript">
Function checkvalid ()
{
VaR A = Document. testform.;
If (A. value. length> 20)
{
Alert ("the length of the input remarks box cannot exceed 20 characters! ");
Return false;
}
Return true;
}
3. The onpropertychange attribute cannot be used to determine the number of accurate words after copy.
Onpropertychange can be used to determine the value of a predetermined element. When the value of an element changes, the event will be triggered. It only cares about the value of the monitored element.
Value, avoiding the input source, so that we can achieve our goal of limiting the number of words. It belongs to the JS category and can be nested in the box representation of the form. The following isCodeAnd effect Samples
You can test the input as above, and you will find that it achieves the goal: No matter how you enter it, it can only enter 100 characters (Chinese characters or other small-decoding symbols ):
Code:
<Textarea onpropertychange = "If (value. length> 100)
Value = value. substr (0,100) "class =" smallarea "Cols =" 60 "name =" txta"
Rows = "8"> </textarea>
4. Call the js method in the onkeyup, onkeydown, and onpaste events of <textarea>, for example:
You can also enter 140 words
onkeyup =" checklength () "onpaste =" checklength () ">
Function checklength (){
VaR value = Document. getelementbyid ("talktopic"). value;
If (value. length> 140 ){
Document. getelementbyid ("talktopic"). value = Document. getelementbyid ("talktopic"). value. substr (0,140 );
} Else {
Document. getelementbyid ("validnum"). innerhtml = 140-value. length;
}
}
In checklength (), verify the length of textarea. If the length exceeds the limit, take the first 140 characters.