In this example, I will tell you how to implement character count and apply validation for maximum character length in textarea.
This is very useful to let you know how many characters you type into the field.
For example, for SMS field you know what limitation is required to send message by using SMS Api, there you can apply the max length validation.
You can customize the text message of remaining characters as well you can customize their position.
Bootstrap Maxlength is a very awesome jQuery plugin to validate character count on client side.
Let's have a example :
- <!DOCTYPE html>
- <html>
- <head>
- <title>Bootstrap Maxlength Validation with Example</title>
- <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
- <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-maxlength/1.7.0/bootstrap-maxlength.min.js"></script>
- </head>
- <body>
- <div class="row">
- <div class="col-md-offset-3 col-md-6">
- <div class="form-group">
- <textarea class="form-control" placeholder="Type here to see how it work" maxlength="100"></textarea>
- </div>
- </div>
- </div>
- <script type="text/javascript">
- $('textarea').maxlength({
- alwaysShow: true,
- });
- </script>
- </body>
- </html>
Now we will change the position of counter at top left, you can place the counter indicator on top-right, bottom-left etc.
- <script type="text/javascript">
- $('textarea').maxlength({
- alwaysShow: true,
- placement: 'top-left'
- });
- </script>
You can also customize the message by following way:
- <script type="text/javascript">
- $('textarea').maxlength({
- alwaysShow: true,
- threshold: 10,
- warningClass: "label label-success",
- limitReachedClass: "label label-danger",
- separator: ' out of ',
- preText: 'You write ',
- postText: ' chars.',
- validate: true,
- placement: 'bottom-left'
- });
- </script>