Oct
20
2011

Simple Textarea Word Counter jQuery Plugin

by   |  Posted in Downloads  |  13 comments

I know there are a few textarea word counter jQuery plugins out there already, but I felt like building my own since I wasn’t a fan of the ones that are available. Nothing new here but I did my best at making it as simple to use and efficient as possible.

/**
 * jQuery.textareaCounter
 * Version 1.0
 * Copyright (c) 2011 c.bavota - http://bavotasan.com
 * Dual licensed under MIT and GPL.
 * Date: 10/20/2011
**/
(function($){
	$.fn.textareaCounter = function(options) {
		// setting the defaults
		// $("textarea").textareaCounter({ limit: 100 });
		var defaults = {
			limit: 100
		};	
		var options = $.extend(defaults, options);
 
		// and the plugin begins
		return this.each(function() {
			var obj, text, wordcount, limited;
 
			obj = $(this);
			obj.after('<span style="font-size: 11px; clear: both; margin-top: 3px; display: block;" id="counter-text">Max. '+options.limit+' words</span>');
 
			obj.keyup(function() {
			    text = obj.val();
			    if(text === "") {
			    	wordcount = 0;
			    } else {
				    wordcount = $.trim(text).split(" ").length;
				}
			    if(wordcount > options.limit) {
			        $("#counter-text").html('<span style="color: #DD0000;">0 words left</span>');
					limited = $.trim(text).split(" ", options.limit);
					limited = limited.join(" ");
					$(this).val(limited);
			    } else {
			        $("#counter-text").html((options.limit - wordcount)+' words left');
			    } 
			});
		});
	};
})(jQuery);

Load that up and then you can use the following to make it work:

$("textarea").textareaCounter({ limit: 100 });

The default limits to 100 words but you can change that to whatever you like. Here is a simple HTML setup using the plugin:

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
/**
 * jQuery.textareaCounter
 * Version 1.0
 * Copyright (c) 2011 c.bavota - http://bavotasan.com
 * Dual licensed under MIT and GPL.
 * Date: 10/20/2011
**/
(function($){
	$.fn.textareaCounter = function(options) {
		// setting the defaults
		// $("textarea").textareaCounter({ limit: 100 });
		var defaults = {
			limit: 100
		};	
		var options = $.extend(defaults, options);
 
		// and the plugin begins
		return this.each(function() {
			var obj, text, wordcount, limited;
 
			obj = $(this);
			obj.after('<span style="font-size: 11px; clear: both; margin-top: 3px; display: block;" id="counter-text">Max. '+options.limit+' words</span>');
 
			obj.keyup(function() {
			    text = obj.val();
			    if(text === "") {
			    	wordcount = 0;
			    } else {
				    wordcount = $.trim(text).split(" ").length;
				}
			    if(wordcount > options.limit) {
			        $("#counter-text").html('<span style="color: #DD0000;">0 words left</span>');
					limited = $.trim(text).split(" ", options.limit);
					limited = limited.join(" ");
					$(this).val(limited);
			    } else {
			        $("#counter-text").html((options.limit - wordcount)+' words left');
			    } 
			});
		});
	};
})(jQuery);
</script>
</head>
 
<body>
	<textarea rows="15" cols="50"></textarea>
 
	<script type="text/javascript">
	$("textarea").textareaCounter();
	</script>
 
</body>
</html>

That would give you a textarea box that looks like this:

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.
If you require help or support, please visit the Support Forum and ask all your questions there. Questions about themes or plugins posted in the comments below will not be answered.

Tags: , , ,

Short URL: http://bit.ly/orrtjk

Discussion 13 Comments

  1. Schallzahnbürste on November 12, 2011 at 8:51 am

    Nice one. This would be very usefull in the backend of WordPress and a minimum limit instead of maximum.

  2. sunil on November 28, 2011 at 9:43 am

    this is the best Jquery plugin….

    Thanx a lot

  3. Radoslav on December 13, 2011 at 3:31 pm

    Try write one word on first line and then press ENTER and write other word.. Countdown does not work correctly..

    • c.bavota on December 21, 2011 at 7:55 am

      That is a small bug. I’m doing some tests to find a solution. Thanks for pointing that out.

    • jaime on January 18, 2012 at 3:43 pm

      i’ve been using a regular expression to split at spaces and line breaks:

      $.trim(text).split(/[\s\n\r]+/).length
    • c.bavota on January 19, 2012 at 1:05 pm

      @jaime I tried your solution but it didn’t work.

  4. Steuerberater Berlin on December 27, 2011 at 1:06 pm

    Thanks. I am going to have a go at this one. Looks good

  5. Jayshankar Krish on December 29, 2011 at 12:59 pm

    Thanks for the wonderful plugin, will be very helpful and keep up the gr8 work going, God bless you for this kind gesture. Take care!!!

  6. dynamics crm on January 4, 2012 at 1:39 pm

    Great job with building the textarea word counter jQuery plugin. I’ve tried many textarea word counter jQuery plugins before. Yours seems pretty simple to use. I can’t wait to try it out on my website.

  7. jim on January 4, 2012 at 5:28 pm

    Thanks for the great plugin! Awesome!

  8. Simon on January 8, 2012 at 10:27 am

    Exactly what I needed for one of my projects, thank you!

  9. Phil Rae on January 27, 2012 at 7:49 pm

    Hi,

    I found a couple of small bugs when trying to add your plugin to a form with multiple textareas that need to be validated.

    Firstly, a simple one – the line:

    if(wordcount > options.limit) {

    Should actually read

    if(wordcount >= options.limit) {

    This is because the first version will never be true because you are not allowed to be higher than the limit, and therefore your “0 words left” red text will never show.

    The second issue is that your #counter-text span is set using an ID name. This is wrong as you are not able to have multiple textareas to check as when you edit any textarea past the first one, the count of words in the current textarea field will cause the count on the first textarea to update. Therefore you should change “counter-text” to be a class name, then use the ‘obj’ object to locate its nearest counter-text span to update. Therefore the whole plugin should now read:

    (function($){
    	$.fn.textareaCounter = function(options) {
    		// setting the defaults
    		// $("textarea").textareaCounter({ limit: 100 });
    		var defaults = {
    			limit: 100
    		};	
    		var options = $.extend(defaults, options);
     
    		// and the plugin begins
    		return this.each(function() {
    			var obj, text, wordcount, limited;
     
    			obj = $(this);
     
    			obj.after('Max. '+options.limit+' words');
     
    			obj.keyup(function() {
    			    text = obj.val();
    			    if(text === "") {
    			    	wordcount = 0;
    			    } else {
    				    wordcount = $.trim(text).split(" ").length;
    				}
    			    if(wordcount >= options.limit) {
    			        obj.parent().find(".counter-text").html('0 words left');
    					limited = $.trim(text).split(" ", options.limit);
    					limited = limited.join(" ");
    					$(this).val(limited);
    			    } else {
    			        obj.parent().find(".counter-text").html((options.limit - wordcount)+' words left');
    			    } 
    			});
    		});
    	};
    })(jQuery);

    I hope that helps some people who are trying to add multiple text areas. Thanks for a great plugin though – other than those two bugs, it worked a treat!

    • Phil Rae on January 27, 2012 at 8:01 pm

      Hi, me again. I just realise that when you reload a page with a textarea already populated with text, it doesn’t show the current ‘words left’ until you start typing. Therefore I’ve amended the plugin slightly so that if the field is not empty on page load, it performs the word count check, just as you have on keyup. Edit below…

      (function($){
      	$.fn.textareaCounter = function(options) {
      		// setting the defaults
      		// $("textarea").textareaCounter({ limit: 100 });
      		var defaults = {
      			limit: 100
      		};	
      		var options = $.extend(defaults, options);
       
      		// and the plugin begins
      		return this.each(function() {
      			var obj, text, wordcount, limited;
       
      			obj = $(this);
       
      			obj.after('Max. '+options.limit+' words');
       
      			// function to check word count in field			
      			var countcheck = function() {
      		    text = obj.val();
      		    if(text === "") {
      		    	wordcount = 0;
      		    } else {
      			    wordcount = $.trim(text).split(" ").length;
      				}
      		    if(wordcount >= options.limit) {
      		      obj.parent().find(".counter-text").html('0 words left');
      					limited = $.trim(text).split(" ", options.limit);
      					limited = limited.join(" ");
      					$(this).val(limited);
      		    } else {
      		      obj.parent().find(".counter-text").html((options.limit - wordcount)+' words left');
      		    } 
      			}
       
      			// if field is not empty, count words
      			if(obj.val() != '') {
      				countcheck(); }
       
       			// if field changes, count words
      			obj.keyup(function() {
      				countcheck(); });
      		});
      	};
      })(jQuery);

Leave a Reply

Your email address will not be published. Required fields are marked *

*


To enter code in the comment box, please place it between <pre lang="php"> </pre> tags. You don't have to convert any characters to their hex/HTML code. Just add your code the way you would to any code editor.