jQuery tips & tricks: how to limit characters inside a textarea

You might have come across a problem trying to limit the maximum number of characters in a text area, since a maxlength attribute doesn’t exist for this tag. In this article we will provide you with a jQuery-based solution, one that is fully functional and usable.
The concept is based on counting all the characters in a text area every time you release a keystroke without allowing any more characters to be added. At the same time, we will calculate the difference between the maximum number of characters allowed and their actual number, thereby showing us in realtime the number of characters remaining. You can see the final result in this example page.
The importance of doing client checks on a form
When we carry out client checks(as in this example) on a form, we must be aware that we are doing it solely to help the user, to make the site more usable. It is very important to note that client checks are easily bypassed, so the real check-up (length, format, etc.) must be done on a server. Having said this, we can move on to the main subject.
Setting up the page
Let’s begin by setting up a text area form inside a new html page. Next we will add a blank div (#counter), containing a phrase on the number of characters remaining.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// here we will write-up the function
});
</script>
</head>
<body>
<form id="input_form" method="POST" action="?">
<textarea id="text"></textarea>
<input type="submit" value="submit">
</form>
<div id="counter"></div>
</body>
</html>
Now we are ready to write up the function. Let’s start by defining the character variable which stands for the maximum number of characters that a text area can contain. Next let’s write up the phrase in the counter element.
var characters= 100;
$("#counter").append("You have <strong>"+ characters+"</strong> characters remaining");
Now every time that the keyup event takes place (everytime you release a keystroke) we will proceed with the check-up:
$("#text").keyup(function(){
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
This check-up can look quite complex, but we will see in a moment what it’s all about.
With $(this).val() we extract the actual content of the textarea (at the time of keyup) and length gives us the number of characters. If this number is greater than what we’ve set in the character variable (100 in this case), the textarea content will have to be the same as the textarea content which passed through the substr function with parameters 0, and characters.
The substr function cuts off a piece of the string; parameters indicated where the characters begin and end by being cut off. Thus in our case it begins at 0 (the beginning of the string) and ends at characters (character 100).
Summing up: if the length of the string contained in the textarea is greater than the maximum number we’ve set, you should cut the string at a length equal to the maximum number of set characters.
Now let’s change the phrase with the remaining number of characters:
var remaining = characters - $(this).val().length;
$("#counter").html("You have <strong>"+ remaining+"</strong> characters remaining");
Here we will simply subtract the number of characters written in the textarea from characters and we will insert the resulting phrase in the counter element.
Let’s add a little tweak. If the number of remaining characters is less than ten, the phrase will be written in red, in the following way:
if(remaining <= 10)
{
$("#counter").css("color","red");
}
else
{
$("#counter").css("color","black");
}
The final script should look like this:
$(document).ready(function() {
var characters = 220;
$("#counter").append("You have <strong>"+ characters+"</strong> characters remaining");
$("#text").keyup(function(){
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
var remaining = characters - $(this).val().length;
$("#counter").html("You have <strong>"+ remaining+"</strong> characters remaining");
if(remaining <= 10)
{
$("#counter").css("color","red");
}
else
{
$("#counter").css("color","black");
}
});
});
jQuery: the logic behind extensions
Now that we have a script which we can use more than once, it’s only right to follow the logic behind jQuery and turn it into a plugin.
Let’s begin by setting up the structure of the plugin:
(function($){
$.fn.limit = function(options) {
Our method is called limit and it can run various parameters. Let’s start by setting up the default ones
var defaults = {
limit: 200,
id_result: false,
alertClass: false
}
As you can see, parameters will be the maximum number of characters, the element id containing the phrase which indicates the remaining number of characters (by default this does not exist) and the css class which determines the color (and/or other attributes) which will affect the text if there are less than 10 characters.
This method is correct, more so than the one we saw earlier. In fact who said that the text should become red? Furthermore who said that text should be in black from the very beginning? In this way, we will not use css methods but addClass and removeClass so that the style can be configured directly from css.
Now let’s enhance the options available:
var options = $.extend(defaults, options);
Now let’s write up the function being careful in printing out the phrase only if the id_result parameter has been enhanced:
return this.each(function() {
var characters = options.limit;
if(options.id_result != false)
{
$("#"+options.id_result).append("You have <strong>"+ characters+"</strong> characters remaining");
}
$(this).keyup(function(){
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
if(options.id_result != false)
{
var remaining = characters - $(this).val().length;
$("#"+options.id_result).html("You have <strong>"+ remaining+"</strong> characters remaining");
if(restanti <= 10)
{
$("#"+options.id_result).addClass(options.alertClass);
}
else
{
$("#"+options.id_result).removeClass(options.alertClass);
}
}
});
});
Here is the plugin in complete form:
(function($){
$.fn.limit = function(options) {
var defaults = {
limit: 200,
id_result: false,
alertClass: false
}
var options = $.extend(defaults, options);
return this.each(function() {
var characters = options.limit;
if(options.id_result != false)
{
$("#"+options.id_result).append("You have <strong>"+ characters+"</strong> characters remaining");
}
$(this).keyup(function(){
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
if(options.id_result != false)
{
var remaining = characters - $(this).val().length;
$("#"+options.id_result).html("You have <strong>"+ remaining+"</strong> characters remaining");
if(remaining <= 10)
{
$("#"+options.id_result).addClass(options.alertClass);
}
else
{
$("#"+options.id_result).removeClass(options.alertClass);
}
}
});
});
};
})(jQuery);
Now, if we wanted to obtain the same result we witnessed in the first part by using the plugin, we will have to include this plugin and modify the code in the following way (let’s remember to create a css class):
<script type="text/javascript" src="jquery-1.4.1.js"></script>
<script type="text/javascript" src="jquery.limit.js"></script>
<style>
.alert{
color: red;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("#testo").limit({
limit: 100,
id_result: "counter",
alertClass: "alert"
});
});
</script>
Versione: 1.0
Pubblicato: 16 May 2010
Dimensione: 912 bytes
Download: JQueyLimit
Conclusion
We’ve just looked at the beautiful modularity of jQuery. Any problem, recurring ones included, can be resolved with an extension. If we adopt this approach, we could end up creating a huge collection of plugins. Their use in the code provides for easy reading and aesthetically pleasing as well.
In this article we’ve described a possible procedure to use to limit the length of a text inside a text area.
Did you ever come across a similar procedure? How did you manage to solve the embedded problem?
*****************************************
L'immagine principale dell'articolo è stata fornita da @Fotolia
21 comments
Trackback e pingback
-
Tweets that mention jQuery tips & tricks: how to limit characters inside a textarea | Your Inspiration Web -- Topsy.com
[...] This post was mentioned on Twitter by Paul, nando pappalardo, Your Inspiration Web, Tom Bangham, V. Tavares (E-Goi) and ... -
Element with jquery |Avnish Namdev
[...] [ 11 Comments ] [...]



Nice tips. Another way to limit and provide character count feedback when users are typing is a plugin I created a little while ago, NobleCount @ http://tpgblog.com/noblecount/
You should check it out; has some nice flexibility and functionality that may also be what you are looking for.
Let me know what you think.
Jeremy Horn
The Product Guy
http://tpgblog.com
Thanks Jeremy Horn.
Very nice tutorial and well done plugin
really helping with some techniques. thanks for sharing
I am glad you both useful
Wow this is a great resource.. I’m enjoying it.. good article
Thanks cna training
Hi! I simply wanted to say your website is one of the nicely laid out, most inspirational I’ve come across in quite a while. Thx!
Thank you so much Frances.
Here is a nice description both using ASP.NET Code (server side) and jQuery (client side)
http://www.itfunda.com/how-to-limit-the-maximum-number-of-characters-allowed-in-the-multiline-textbox/Free/20
Great tutorial! Many Thanks Maurizio!
Very nice tutorial and very nicely laid out blog, everything is in perfect place.
Thanks Maurizio
works perfectly, thanks a looooot for this script…!
wow, not only you solved my problem but also taught me how to turn nice little scripts into a plugin. hats off sir
Thanks a lot!
Thanks for a good script and an easy way to help me figure out how to create plugins. Two birds with one stone! (I was looking for the textarea limiter)
Thanks heaps, this was a really easy tutorial to follow. Gotta love jQuery!
Sorry to say it does not work
Hi,
Thanks a lot for the script. We might need to handle drag and drop too. I can select a text from webpage or from notepad and drag more characters than allowed into textarea. Later I could tabout of the textarea.
Thanks,
-Jana
Hello, it is great tutorial, but i have one question about jquery and html5, now is different, will it be working for ie8 ? I did it with
and for html5 and use your
$(document).ready(function() {
var characters = 400;
$(“#counter”).append(“Tu tienes “+ characters+” carácteres restantes”);
$(“#message”).keyup(function(){
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
var remaining = characters – $(this).val().length;
$(“#counter”).html(“Tu tienes “+ remaining+” carácteres restantes”);
if(remaining <= 10)
{
$("#counter").css("color","red");
}
else
{
$("#counter").css("color","black");
}
});
});
and the plugin you did jquery.limit.js
Hope your answer soon as possible
greetings!
Citlalli
how about to limit the reply content in comment in dashboard