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 lengthgives us the number of characters. If this number is greater than what we’ve set in the charactervariable (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 atcharacters (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");}
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?
If you liked my post then,
Click here to Subscribe to FREE email updates from "itrickz", so that you do not miss out anything that can be valuable to you and your blog!!
0 comments: on "jQuery tips & tricks: how to limit characters inside a textarea"
Post a Comment