jQuery Word/Character Counter

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 thecounter 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.

 

http://www.jamesfairhurst.co.uk/posts/view/jquery_word_character_counter/

Leave a comment