Quantcast
Channel: edrackham » jQuery
Viewing all articles
Browse latest Browse all 4

How to Create a Textarea Character Counter / Limiter Using jQuery

$
0
0

Need to limit the number of characters that are allowed to be entered into a textarea? I’ve crafted a little snippet that you can drop into your projects to achieve just that! It also provides a counter to the user, showing how many characters are remaining as they type.

This could be extended pretty easily, so that it works on multiple textareas, or even as a jQuery plugin.

Show Me the Code

If you don’t need to read the breakdown of this tutorial, you can simply just copy the code below and read no further!

The Javascript

<script type="text/javascript" src="http://www.google.com/jsapi"></script>

<script type="text/javascript" language="javascript">
google.load("jquery", "1.4.2");

var characterLimit = 150;

google.setOnLoadCallback(function(){
	
	$('#remainingCharacters').html(characterLimit);
	
	$('#myTextarea').bind('keyup', function(){
		var charactersUsed = $(this).val().length;
		
		if(charactersUsed > characterLimit){
			charactersUsed = characterLimit;
			$(this).val($(this).val().substr(0, characterLimit));
			$(this).scrollTop($(this)[0].scrollHeight);
		}
		
		var charactersRemaining = characterLimit - charactersUsed;
		
		$('#remainingCharacters').html(charactersRemaining);
	});
});
</script>

The HTML


characters remaining.

So, How Does It All Work?

Let’s start with the HTML markup. It’s pretty simple, we’re just creating a textarea, with an ID of myTextarea. We also have a paragraph below that, which has an empty span with an ID of remainingCharacters. This is where the remaining characters will be displayed to the user as they type.

Google JSAPI

The Javascript is a little more involved. Let’s go line-by-line:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>

I’ve recently started using the Google JSAPI to link to my most-used Javascript libraries. For those who don’t know what the Google JSAPI is – have a read here. I prefer to load jQuery this way for a number of reasons:

  • It’s always hosted in the same place – so no having to traverse your own paths to find where your JS libraries are located
  • It saves bandwidth
  • It seems to load much faster
  • It’s very easy to bolt on other libraries you may need
<script type="text/javascript" language="javascript">
google.load("jquery", "1.4.2");

Here, we’re starting our main Javascript block, and – using the Google JSAPI – we’re loading the jquery library, version 1.4.2.

Variable Limit

var characterLimit = 150;

Real simple here – we’re setting a global variable to the value of our limit for the textarea. Feel free to change this value to whatever you wish.

What? No $(document).ready()?

google.setOnLoadCallback(function(){

Nope. When you use the Google JSAPI, you should really use google.setOnLoadCallback(). This is due to the way we’re loading the jQuery. $(document).ready() may actually provide a false-positive, and execute before the jQuery has been fully loaded – therefore we should use the google on load callback – which fires once all the libraries we have requested have been included.

Set the Starting Figure

$('#remainingCharacters').html(characterLimit);

As our remainingCharacters span in our HTML markup is empty, we need to set the value when the page loads. We could hard-code the value of the remaining characters, but this would mean that we’d have to update two places if we wanted to change the limit, not just one (the one place we need to update the character limit is on the var characterLimit = 150; line).

Binding It All Up

$('#myTextarea').bind('keyup', function(){
	var charactersUsed = $(this).val().length;
	
	if(charactersUsed > characterLimit){
		charactersUsed = characterLimit;
		$(this).val($(this).val().substr(0, characterLimit));
		$(this).scrollTop($(this)[0].scrollHeight);
	}
	
	var charactersRemaining = characterLimit - charactersUsed;
	
	$('#remainingCharacters').html(charactersRemaining);
});

The final bit, this bind is where all the magic happens. Firstly we’re binding a function to the ‘keyup’ event on the element named myTextarea.

Inside this function we need to know how many characters have been used. We do this by calling the following:

var charactersUsed = $(this).val().length;

Notice how we can use $(this) to reference the myTextarea element. This is a nice little bit of shorthand that comes in handy – often!

if(charactersUsed > characterLimit){
	charactersUsed = characterLimit;
	$(this).val($(this).val().substr(0, characterLimit));
	$(this).scrollTop($(this)[0].scrollHeight);
}

We then have this if statement which checks to see if the number of characters used is greater than our preset character limit. If it is greater, we know that the user has gone over their limit, and we need to do something about that. We need to trim any extra characters past our limit, and reset the focus to the bottom of the textarea. We need to set the focus to the bottom again, because when you update the text within a textarea, the focus jumps back to the top!

Letting the User See How Many Characters Remain

var charactersRemaining = characterLimit - charactersUsed;
	
$('#remainingCharacters').html(charactersRemaining);

Fairly self explanatory here – we do a quick calculation to determine how many characters remain, and then update the remainingCharacters span, so the user can see how much more they can type.

Remember, this gets updated every time they key is released from within the textarea.

That concludes this tutorial! I hope it’s helped in some way. I may even release this as a simple jQuery plugin that can be used on any number of textareas.


Viewing all articles
Browse latest Browse all 4

Trending Articles