In this post, i will let you know how to count number of characters limit in textarea and show the available remaining characters that you can enter.
For example, If you are going to send SMS from application then there you can use this validation for apply characters limit.
In this example, you will know the use of onkeyup
and onkeydown
event.
onkeyup
event is triggered when a keyboard key is released and onkeydown
event is triggered when a keyboard key is pressed.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Javascript Maxlength Validation with Example</title>
- </head>
- <body>
- <form>
- <textarea name="message" placeholder="Type here to see how it work" onkeydown="limitText(this.form.message,this.form.countdown,160);" onkeyup='limitText(this.form.message,this.form.countdown,160);'></textarea>
- You have
- <input readonly type="text" name="countdown" size="3" value="160"> chars left
- </form>
- <script type="text/javascript">
- function limitText(limitField, limitCount, limitNum) {
- if (limitField.value.length > limitNum) {
- limitField.value = limitField.value.substring(0, limitNum);
- } else {
- limitCount.value = limitNum - limitField.value.length;
- }
- }
- </script>
- </body>
- </html>
Click here to know the Javascript Bootstrap - Textarea count characters validation with example