jQuery Word/Character Counter

7th August 2008 jQuery

Just a quick jQuery post that calculates the number of words/characters in a form input field. Needed one of these recently for a work project and its really easily to implement and works like a charm

The HTML

Below is a very simple form which has a single form input which is located inside a div, along with a label and a span named counter which will be used to display the number of words/characters exist in the input. As with anything in HTML you can style the form accordingly with CSS and this can include hiding the counter entirely if desired.

<form action="" method="post">
	<fieldset>
	<legend>Sample Form</legend>

	<div class="input">
		<label>Text:</label>
		<span class="counter"></span>
		<input type="text" name="field1" id="field1" class="word_count" />
	</div>
	
	<div class="input">
		<input type="submit" name="submit" id="submit" value="Submit" />
	</div>

	</fieldset>
</form>

The Javascript

Obviously you'll need the jQuery javascript library before this code will work, so go to the main website, download the library and include it in your html.

The following code loops through the page looking for word_count classes, calculates the current number of characters in the input field and then updates the counter class located inside the input div.

It then attaches a keyUp() event handler to run every time a key is released, once this happens the code recalculates the number of characters inside the form input and redisplays the value inside the counter class.

The code below also includes the logic to display the number of actual words but this has been commented out.

$(document).ready(function(){

/**
 * Character Counter for inputs and text areas
 */
$('.word_count').each(function(){
	// get current number of characters
	var length = $(this).val().length;
	// get current number of words
	//var length = $(this).val().split(/\b[\s,\.-:;]*/).length;
	// update characters
	$(this).parent().find('.counter').html( length + ' characters');
	// bind on key up event
	$(this).keyup(function(){
		// get new length of characters
		var new_length = $(this).val().length;
		// get new length of words
		//var new_length = $(this).val().split(/\b[\s,\.-:;]*/).length;
		// update
		$(this).parent().find('.counter').html( new_length + ' characters');
	});
});

});

Wrapping Up

Like I said a short post that does exactly what it says on the tin.

Back to Home Page

Comments

Newton (14/06/2009 - 05:34)

Thanks. This works great! It even dislays the character count when the page is reloaded and the textarea is populated with previous data.

EllisGL (25/06/2009 - 08:38)

Don't use classes for your selector. I've updated script to be a lot faster.
$(document).ready(function()
{
$('#field1').each(function()
{
// get current number of characters
var length = $(this).val().length;

$('#counter').html(length + ' characters');

}).keyup(function()
{
// get new length of characters
var new_length = $(this).val().length;
$('#counter').html( new_length + ' characters');
});
});

EllisGL (25/06/2009 - 08:41)

Er: This is my final version:
$(document).ready(function()
{
// get current number of characters
$('#counter').html($('#field1').val().length + ' characters');

$('#field1').keyup(function()
{
// get new length of characters
$('#counter').html($(this).val().length + ' characters');
});
});

James (25/06/2009 - 11:58)

@EllisGL: Hi thanks for that, using Ids is indeed much faster because jQuery uses the existing getElementById() javascript method. I read about this lately so thanks for coming up with a better version :)

Francis (05/07/2009 - 11:04)

Hi,

This is nice but I'm seeking for a solution to count "real" character in a rich text box (i.e. in an html text, skipping all tags). Do you hava en idea ?

Regards,

Francis

James (08/07/2009 - 23:15)

@Francis: Hi and thanks for commenting, the only solution I can think of would be to send all the html to a php script via ajax and strip all the html using the php "strip_tags" function. Then you will be able to get the real character count.

HostPipe Web Design (15/07/2009 - 09:25)

Thanks for the great resource, am slowly learning how best to make use of JQuery, and your character count code above was top of Google...good work, saved me a lot of time indeed.

Rob

Martin (17/07/2009 - 09:39)

Using IDs may be faster, but you shouldn't use the same ID for different elements, it should be unique. Although most browsers can handle repeated IDs, they don't have to.

Patrick (08/09/2009 - 11:00)

This may be kind of old, but just to throw it out there. Classes may be your best option if your not working with straight HTML and instead are creating your control serverside using .net. Not exactly easy to tell the server what clientid you want the control to have.

Katie (23/09/2009 - 13:52)

This is great!

I got the first version of the code to work well with some customizations and such. (Note: I'm a n00b)

However, I'd like to use the final version of the code but I can't get it to work. How do I implement the updated code in the HTML without using the word_count class? In other words, what's the HTML?

Thanks!!!

James (23/09/2009 - 23:44)

@Katie: Hey thanks for commenting, I think you will be fine using the base code however using id's you will just need to assign an id to the textarea like this:

<textarea id='wordcount'></textarea>

And then in jquery get the element using "$('#wordcount')", the only issue here is that Id's should be unique to a single element and that's why I used CSS Classes to identify which textareas the counter should be on.

Hope that helps

Will (16/12/2009 - 13:39)

I created a plugin that is a bit more advanced than this and has some sweet options. Check it out! http://plugins.jquery.com/project/word-and-character-counter

Ken (20/01/2010 - 10:52)

Thanks!! This works very well. However, I am getting a warning message from Firebug that says "The 'charCode' property of a keyup event should not be used. The value is meaningless.". I'm not sure what this means or how to correct it. Any ideas?

Priya (12/02/2010 - 12:10)

Thanks for sharing this util. worked for the very first time without any hassle. I needed something similar and had to enhance it to do 2 more things
1. Added a maximum limit of characters.
2. Added a reverse counter for showing characters left.

<a href="http://software-wikipedia.blogspot.com/2010/02/jquery-maximum-limit-texttextarea-with.html" > Here is my post for same</a>

Thanks again for your quick handy code.

Pratik (22/02/2010 - 03:07)

Helo i am pratik
I am facing one prob with validation of wordcount of jquery.
i have validation of maximum 10 words. it work completely when we enter text in it.
but if you copy a big pera whose lenegth is large than 10. still it accept.so i want that at a time of pasting extra word should be cut. plz help me as soon as possible..
Than k you

James (22/02/2010 - 04:51)

@Prati: I would check the work count when the user moves focus away from the field, if the word count is greater than 10 then display a warning or automatically decrease the word count. You're on your own for implementation unfortunately.

Will (22/02/2010 - 13:01)

@Pratik. Check out my plugin, it does exactly what you want it to: http://plugins.jquery.com/project/word-and-character-counter

accesinterzis (21/03/2010 - 03:07)

Great, great, great, great (have I forgotten to say "great"?) job. Thanks a lot.

Juan (09/11/2010 - 00:56)

I was figuring out how to do this but couldn't figure it out. I'm kinda new to jQuery itself but not the other stuff out there. Anyways, this looks very good. Thanks.

Add Your Comment

Sites I've Created

DSP Chartered Surveyors Stoneylane Aberdeen Angus

Recently Watched Films

Mr Brooks Rec Pathology Diary of the Dead

TV Shows

The Shield Flight of the Conchords

Hosting

I've been using Dreamhost for my hosting for over 2 years and it's pretty good for what you pay. If you're signing up how about showing me some love and use this link so I get a referal bonus to help pay my server costs.

Site by James Fairhurst © 2008-2012, all rights reserved and all that malarky