Maxlength for textarea using jQuery
If you want to limit the characters your user/visitor can type in an input field, you CAN, using the maxlength attribute. But if you want to limit the characters for textarea, you CAN’T, because it doesn’t support the maxlength attribute like inputs do. So here is a little jQuery script that will make the textarea’s maxlength attribute work.
HTML
<textarea maxlength='20'></textarea>
The jQuery code bellow will have effect to all textareas with maxlength attribute.
jQuery
$(document).ready(function() {
$('textarea[maxlength]').keyup(function(){
//get the limit from maxlength attribute
var limit = parseInt($(this).attr('maxlength'));
//get the current text inside the textarea
var text = $(this).val();
//count the number of characters in the text
var chars = text.length;
//check if there are more characters then allowed
if(chars > limit){
//and if there are use substr to get the text before the limit
var new_text = text.substr(0, limit);
//and change the current text with the new text
$(this).val(new_text);
}
});
});
Related posts:
- Use HTML5 Placeholder Input Attribute Today using jQuery!
- Checking username availability with ajax using jQuery
- Create an AMAZING contact form with no ready made plugins.
- Making a nice jQuery content scroller with ease.
- Advanced jQuery Placeholder Plugin (cross-browser support)
Slobodan Kustrimovic
This author has yet to fill his BIO.
Did you absolutely LOVE this article... share it!
Comments
A similar jQuery plugin for setting Maxlength of a textarea:
http://viralpatel.net/blogs/2008/12/set-maxlength-of-textarea-input-using-jquery-javascript.html
That one doesn’t work with copy paste
Cool code it works! Nice!
new in jQuery.
this script proves the power of jQuery.
thanks for sharing
@Calin – That’s only a little bit of jQuery power.
For extra convience you can also add a counter.
Just add a span somewhere
(Added spaces for display purposes)
And add a litle piece of js:
$(“.remaining”).html((limit – text.length) + ” letters remaining.”);
Or:
$(“.remaining”).html((text.length) + ” letters written.”);
I saw that the blog stripped out the little HTML I punt in… so I’ll explain.
You can just add a span or div with the class “remaining” and it’ll smash in the text there…
You could also make it prettier by doing this:
var chars = text.length;
var charsLeft = limit – text.length;
if(charsLeft < 1 ){
charsLeft = 'No’;
}
$(“.remaining”).html(charsLeft + ” letters left.”);
I added dashes in the hope the span now stays in tact…
Cheers!
Try < and >
Edit:
< and > with the ; at the end
Leave your own!