21
Aug
2012

Twitter like remaining character counter

Posted in: jQuery , No Comments

twiiter-like-counter
We will use jQuery to display characters left when a user starts typing in a text box / text area. A common example of this is twitter’s tweet box where character limit is 140. When user starts typing in tweet box, it displays the number of characters left just before the tweet button.

twiiter-character-counter

Step 1:
Create a text box with character limit of 100. This text box is using ID #textbox
Also add a DIV region which will display the remaining characters.

<textarea id="textbox" rows="8" cols="50" maxlength="100"></textarea>
<div id="remaining_text"></div>

Step 2:
Call jQuery library. I am using Google CDN hosted jQuery library.
You can use alternative method to include jQuery library.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Step 3:
Now add following jQuery code

<script type="text/javascript">
$(document).ready(function() {
var max_text = 100;
$("#remaining_text").html(max_text + ' characters left');
$("#textbox").keyup(function () {
	var text_left = max_text - $(this).val().length; 
    $('#remaining_text').html(text_left + ' characters left');
    });
});
</script>
Explanation of above jQuery code


First we defined the character limit i.e 100 of the text box under variable max_text
And displayed it in div region #remaining_text

Now using jQuery function keyup(), it will count the characters typed and subtract it from the variable max_text and show it in div region #remaining_text

Check Demo!!!

About the Author

Name: Ravi Shekhar
I love learning and sharing web stuffs.

Share this post

Twitter Facebook Google Buzz Digg StumbleUpon Delicious Technorati

Leave a Reply