Restrict Number of Characters with Live Character counter using jQuery

So you would have seen in various websites where users are not allowed to write messages/comments more than certain number of characters. They show you at run time how many characters have been left and you can type only specified number of characters. The best example you would be thinking of is Twitter. Yes you can tweet only up to maximum of 140 characters and it shows you in real time that how many characters you are left with. What if you also want to do something similar in your comment box, message system, or anywhere else in your website?

This simple tutorial will teach you that in simplest possible way using jQuery, to implement this you need not to be tech savvy you can just download the code and get it working in your web applications. Lets start our simple yet useful tutorial.

infotuts word counter


First of all you will have to code your HTML form and then work on textarea (or any other similar field) with jQuery. Below is my simple form with only one <textarea> field.

<div id="demo">
 <form style="width:500px;" id="myform" method="POST" action="#">
 <textarea id="text"></textarea>
 <input type="submit" value="Submit">
<span id="display"></span>
<p style="text-align: justify;">

Now Include  jQuery in your page and then start writing jQuery to control number of characters in textarea of your form. Below is our simple jQuery code to display number of characters left and restrict him from entering any extra characters once he reaches maximum allowed number of characters.

$(document).ready(function() {
 var maxCharAllowed = 140; // Maximum number of characters allowed
 $("#display").append("You are left with <b>"+ maxCharAllowed+"</b> characters");
 if($(this).val().length > maxCharAllowed){ // Compare if still user can enter more characters
 $(this).val($(this).val().substr(0, maxCharAllowed)); // dont let user enter more than allowed number of characters
 var leftCharacters = maxCharAllowed - $(this).val().length;
 $("#display").html("You are left with <b>"+ leftCharacters+"</b> characters");
 if(leftCharacters <= 10)

A little bit of CSS code I have written to ensure it looks good. And the display note turns red when user is left with only 10 characters or less. I hope you guys will like this simple tutorial. There are few cool jQuery plugins to achieve similar functionality but since its a bit of code that can get you functioning so I recommend not to include one extra plugin in your project. Share this cool post with your pals.

About sanjeev

Dreamer, Blogger and Thinker. I love to help people in solving their problems. You can also join me HERE

Related posts: