We available for hire! — Need help with a web or mobile project?
From yensdesign we develop technology projects based on web apps, mobile apps, consulting and databases. We are young and hard workers, passionate about innovation and focused in new technologies.If you want to ask for a budget, we hare available for hire!.
How to set maxlength in textareas by creating a jQuery plugin
January 16th, 2009Hi guys! If you have been reading our own entries lately, maybe you remember an old post titled How to create a plugin for jQuery in which you can see different ways to add functionality to jQuery library. This time we will learn more about that kind of things…
In this tutorial we are going to learn how to create a simple but useful jQuery plugin that allows you to limit the max characters content in your textareas and input text.
You can try the living example before continue reading the tutorial.
Tested in: Firefox, Internet Explorer 6 & 7, Opera, Safari & Chrome.
Let’s go!
Introduction
If you didn’t notice, textareas haven’t the maxlength property, wich is important, you can’t limit the user’s input. It’s not a trouble when the program going to insert the text in the database, because we can truncate the text, however, it can be confusing for the our users because the saved data won’t be the same that they have written.
Creating and using this plugin we will be allowed to limit user’s input in textareas (and inputs), they will be a little less confused
Step 1: Fast! Layout and style
In this tutorial all the important part is in the javascript, so take a fast! look at the html code that we will use:
[code language="html"][/code]Let's try some examples
Write your full name (max. 20 chars)
Write your description (max. 100 chars)
And another fast! look to the CSS:
[code language="css"] @CHARSET "UTF-8"; /******* GENERAL RESET *******/ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { border: 0pt none; font-family: inherit; font-size: 100%; font-style: inherit; font-weight: inherit; margin: 0pt; padding: 0pt; vertical-align: baseline; } body{ line-height: 14px; font-size: 12px; background: #fff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; margin: 0pt; cursor: default; } table{ border-collapse: separate; border-spacing: 0pt; } caption, th, td{ font-weight: normal; text-align: left; } blockquote:before, blockquote:after, q:before, q:after{ content: ""; } blockquote, q{ quotes: "" ""; } input, textarea, select{ font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px; } strong{ font-weight: 700; } ul{ list-style: outside; } a{ cursor: pointer; color: #296ba5; text-decoration: none; } .clear{ clear: both; height: 0; visibility: hidden; display: block; } /******* /GENERAL RESET *******/ h1{ font-weight: 700; font-size: 18px; line-height: 1.2em; border-bottom: 1px dotted #6b9ef1; color: #5f95ef; margin-bottom: 1em; } /******* LOGO *******/ #logo{ text-align: center; margin-top: 1em; display: block; } /******* /LOGO *******/ /******* CONTAINER *******/ #container{ width: 600px; margin: 40px auto; text-align: left; } /******* /CONTAINER *******/ /******* FORM *******/ div.content span{ display: block; font-weight: 700; color: #898989; margin-top: 10px; } div.content{ padding: 0 10px; } input, textarea{ width: 500px; padding: 4px; margin: 5px; font-size: 11px; } /******* /FORM *******/ [/code]
Come on guys! Let’s dive into the interesting part!
Step 2: Extending the jQuery class
As we are going to use the jQuery selectors to add features to HTML elements, we have to add our method int jQuery.fn. Remember the old post:
If we want to create a general function like $.post we must use jQuery object. But if We need to create a new kind of animation for our elements, using the power of the jQuery selectors (for DOM’s elements) we would extend the jQuery.fn object.
Then, the primary code would look like:
[code language="javascript"] jQuery.fn.maxLength = function(max){ this.each(function(){ //Code for each matched element here }); }; [/code]
With this code we are creating a new method called maxLenght which accepts the max number of allowed characteres. Now, you can write the next code in your scripts (although will not do anything):
[code language="javascript"] $("#selector").maxLength(64); [/code]
Step 3: Adding the core code
How to limit the maximum of input characters? In this plugin we use the onkeypress and onkeyup events to check the number of written characteres in each key pulsation. If you make a return false in the onkeypress event, you cancel the entrie of the last character introduced. In the onkeyup event you can’t make this because the event fires when the character was already sent. The core code of this plugin is the below:
[code language="javascript"] jQuery.fn.maxLength = function(max){ this.each(function(){ //Get the type of the matched element var type = this.tagName.toLowerCase(); //If the type property exists, save it in lower case var inputType = this.type? this.type.toLowerCase() : null; //Check if is a input type=text OR type=password if(type == "input" && inputType == "text" || inputType == "password"){ //Apply the standard maxLength this.maxLength = max; } //Check if the element is a textarea else if(type == "textarea"){ //Add the key press event this.onkeypress = function(e){ //Get the event object (for IE) var ob = e || event; //Get the code of key pressed var keyCode = ob.keyCode; //Check if it has a selected text var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd; //return false if can't write more return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection); }; //Add the key up event this.onkeyup = function(){ //If the keypress fail and allow write more text that required, this event will remove it if(this.value.length > max){ this.value = this.value.substring(0,max); } }; } }); }; [/code]
As you can see, the code is easy and fully commented. The only line that requires a special explanation is the line 23, when the event keypress return false to cancel the user input.
The condition allows you write if the text length is minor than the maximum, however, if it is major, there are some keys you can press, as arrow keys, delete keys, etc…Also you can press a key if there is a selected text so the selected text will be erased when you introduce a new character.
The condition also allows you press any key while you are pressing the Control or Alt keys to avoid breaking the navigator shortcuts. You can modify the condition and try to better understand.
Step 4: Trying our new plugin!
That’s all guys, I hope you find it useful and use this tutorial to improve a little more your websites.
You can try the tutorial online here to see how It is working and download here all sources.
Remember that you can solve your doubts in our forums and follow us on Twitter to know more about what are we doing in any moment!
See you on next tutorial and remember that we want you suggest tutorials to write!
Enjoy this post?
Your vote will help us to grow this website and write more entries like this one :)
We available for hire! — Need help with a web or mobile project?
From yensdesign we develop technology projects based on web apps, mobile apps, consulting and databases. We are young and hard workers, passionate about innovation and focused in new technologies. We try to help you, sharing our knowledge acquired on worked projects, while helping the community and showing our capabilities.If you want to ask for a budget, we hare available for hire! Don't doubt in get in touch with us!.
Welcome back Ivan Nice post!
It would have been relatively easy to extend this to “x characters left”, where you would define only the element into which this should be put. Aside from that I wasn’t able to figure out where the name o fthe author is written on this blog, but I may of course simply look over it.
The tutorial is ok, but wouldn’t it be better just to use the “maxlength” property of the “input” tag? I don’t see the advantages of this method.
Hi miguel! The main objective of this plugin is set maxlength in textareas, which has not the maxlength attribute. However, I decided to include the inputs also because it is not costly and it could help sometimes.
Thanks!
[...] Read the rest here: How to set maxlength in textareas by creating a jQuery plugin … [...]
Nice one. But… Still user can right click on text area and paste text. I’m not sure is my remark out of scope. Is there solution for this?
Thanks
The style of writing is quite familiar . Did you write guest posts for other blogs?
I have altered the onKeyUp function so it will update a DIV with an ID of “charleft_[whatever the id of the textarea is]” with the amount of characters left. So, if textarea/field ID is called “comments” then you put HTML like [You have 100 characters left]
this.onkeyup = function(){
//If the keypress fail and allow write more text that required, this event will remove it
if(this.value.length > max){
this.value = this.value.substring(0,max);
}
$(‘#charleft_’+this.id).text(max – this.value.length);
};
thank you for this!!
Hello,
Is there a way to use jQuery selectors to make this even more efficient?
like:
My code:
// pardon the bad code, but this is just for the concept:
#
# $().ready(function(){
# $(“textarea”).maxLength( // get this current textbox’s maxlength value and set it here );
# });
#
Work fine, thank you!
Just created a new file called jquery.maxlength.js include into html and eureka!
Simple and elegant solution!
I recommend!
Oh, one more thing guys, don’t forget to use maxLength with the capitallized L.
korean cars…
[...]How to set maxlength in textareas by creating a jQuery plugin | yensdesign – Tutorials, Web Design and Coding[...]…