Sample Code for textarea to control the number of input characters in bytes

Source: Internet
Author: User

Use the onKeyDown and onKeyUp events of js textarea to monitor user key events in real time, and then use our custom statistical function to calculate the number and number of characters that can be entered.

Real-time statistics html

The Code is as follows: Copy code

<Textarea id = "text" cols = "110" rows = "20" dir = "ltr" onKeyDown = "CountStrByte ()" onKeyUp = "CountStrByte ()"
Onfocus = "if (this. value = 'high quality and professional answers are easier to follow! ') This. value = '';" onblur = "if (this. value ='') this. value = 'high quality and professional answers are easier to follow! '"> High-quality and professional answers are more likely to be noticed! </Textarea>

Js Code,Save the following code as a bKjia. c0m. js file.

The Code is as follows: Copy code

Var LastCount = 0;
Function CountStrByte () {// byte statistics
Var ByteCount = 0;
Var StrValue = ID ('text'). value;
Var StrLength = StrValue. length;
Var MaxValue = 1000;
 
If (LastCount! = StrLength) {// judge here to reduce the number of cycles
For (I = 0; I <StrLength; I ++ ){

ByteCount = ByteCount + 1;

If (ByteCount> MaxValue ){

ID ('text'). innerHTML = StrValue. substring (0, I );
Alert ("the comment content cannot exceed 1000 words! ");

ByteCount = MaxValue;

Break;
}
}
ID ('remain'). innerHTML = MaxValue-ByteCount;
LastCount = StrLength;
}
}

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.