Textarea maxlength with Jquery

The other day I was trying to find a way to limit the amount of characters that a user could enter into a textbox. For some reason you can’t set the maxlength attribute on textareas, so I decided to make this little jquery snippet that truncates a user’s input once they go past a certain limit.


There’s an updated version of this script here

Save this snippet in a js file:

$(document).ready(function(){
	$('textarea[maxlength]').keyup(function(){
		var max = parseInt($(this).attr(’maxlength’));
		if($(this).val().length > max){
			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
		}

		$(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
	});
});

Just download and include jquery like so:

And then include the js file containing the above snippet

Then, to limit a textarea do this:

If you want to show the user the ‘You have x characters remaining’ message, then append an element with the ‘charsRemaining’ class, like so:



You have 255 characters remaining

You have to make sure that the p and textarea elements share the same parent, else the message won’t be updated.

Alex

UPDATE: Thanks for the parseInt() tip Jason
There’s an updated version of this script here

This entry was posted in Programming and tagged , , . Bookmark the permalink.
  • http://www.ampedwebstandards.com Alan

    Thanks for this great example. I modified it and used it with a bunch of text input fields. However, I did not add maxlength to all fields – just the ones that required it. Worked great in IE. However, FF was clearing out the fields that did not have the attribute defined. It appears that the -1 value that FF returns caused the problem, so I had to add a special check for that, to get it to work in both browsers. Thanks again!

  • http://www.ampedwebstandards.com Alan

    Thanks for this great example. I modified it and used it with a bunch of text input fields. However, I did not add maxlength to all fields – just the ones that required it. Worked great in IE. However, FF was clearing out the fields that did not have the attribute defined. It appears that the -1 value that FF returns caused the problem, so I had to add a special check for that, to get it to work in both browsers. Thanks again!

  • Alex

    No problem, I’m glad someone’s found this useful :)

  • Alex

    No problem, I’m glad someone’s found this useful :)

  • Nick

    This is a great script but for some reasons, jquery wouldn’t recognize the maxlength attr on the textarea. Since I was using a constant maxlength across all textareas I was able to get around it, but I wish it would’ve worked like you had! Dunno what the problem was…

  • Nick

    This is a great script but for some reasons, jquery wouldn’t recognize the maxlength attr on the textarea. Since I was using a constant maxlength across all textareas I was able to get around it, but I wish it would’ve worked like you had! Dunno what the problem was…

  • Alex

    Thanks for using it :)
    I’m not sure why it wouldn’t recognise the attribute, sounds very odd.

  • Alex

    Thanks for using it :)
    I’m not sure why it wouldn’t recognise the attribute, sounds very odd.

  • http://jasonseney.tumblr.com Jason

    The maxLength attribute must be parsed into an int to be compared with the length. You can do

    var max = parseInt($(this).attr(‘maxlength’));

    and use the variable max for comparisons throughout the function.

    Hope this helps!

  • http://jasonseney.tumblr.com Jason

    The maxLength attribute must be parsed into an int to be compared with the length. You can do

    var max = parseInt($(this).attr(‘maxlength’));

    and use the variable max for comparisons throughout the function.

    Hope this helps!

  • Alex

    Thanks Jason, updated example accordingly

  • Alex

    Thanks Jason, updated example accordingly

  • Kurtulus Ulker

    $(‘textarea[maxlength]‘).focus(function () {
    if (!document.getElementById(“chrRe”+$(this).attr(‘id’) ))
    {
    var max = parseInt($(this).attr(‘maxlength’));
    var len=$(this).val().toString().length;
    $(this).parent().append(”+(max-len)+’ Karakter Kaldı ‘);
    }

    } );

  • Kurtulus Ulker

    $(‘textarea[maxlength]‘).focus(function () {
    if (!document.getElementById(“chrRe”+$(this).attr(‘id’) ))
    {
    var max = parseInt($(this).attr(‘maxlength’));
    var len=$(this).val().toString().length;
    $(this).parent().append(”+(max-len)+’ Karakter Kaldı ‘);
    }

    } );

  • http://www.callum-macdonald.com/ Callum

    Nice approach. I already use jQuery so I’m trying to figure a quick way to achieve this with jQuery.

    My first hit was this script. It binds the event to both onkeyup and onchange because it’s possible to insert text into a textarea without pressing a key (copy / paste for example).

    That might require the creation of a new function in jQuery as I don’t think one can simultaneously apply one function to both onkeyup and onchange.

  • http://www.callum-macdonald.com/ Callum

    Nice approach. I already use jQuery so I’m trying to figure a quick way to achieve this with jQuery.

    My first hit was this script. It binds the event to both onkeyup and onchange because it’s possible to insert text into a textarea without pressing a key (copy / paste for example).

    That might require the creation of a new function in jQuery as I don’t think one can simultaneously apply one function to both onkeyup and onchange.

  • http://viralpatel.net viralpatel.net

    Hi Alex,
    Nice tutorial.
    I had made similar jQuery plugin to set maxlength of the textarea. See this: Setting Maxlength of Textarea using jQuery.

    Do post tutorials frequently.. Waiting to see more..

  • http://viralpatel.net viralpatel.net

    Hi Alex,
    Nice tutorial.
    I had made similar jQuery plugin to set maxlength of the textarea. See this: Setting Maxlength of Textarea using jQuery.

    Do post tutorials frequently.. Waiting to see more..

  • http://www.holycrap.ws ProLoser

    Actually I’d kinda recommend you scrap this approach and look into input ‘masking’ as that is pretty much what you’re doing. There is even a plugin already bundled for jquery to apply masking in a much more versatile fashion.

    Here’s the best plugin: http://plugins.jquery.com/project/meioMask

    I found it when I used some other stuff he developed for cakePHP.

    This will allow you to do what you did in 1 line of code and is more configureable in that you can have dates autoformat as you type with slashes being inserted around the letters and allow certain characters/numbers in whatever order/count you wish.

  • http://www.holycrap.ws ProLoser

    Actually I’d kinda recommend you scrap this approach and look into input ‘masking’ as that is pretty much what you’re doing. There is even a plugin already bundled for jquery to apply masking in a much more versatile fashion.

    Here’s the best plugin: http://plugins.jquery.com/project/meioMask

    I found it when I used some other stuff he developed for cakePHP.

    This will allow you to do what you did in 1 line of code and is more configureable in that you can have dates autoformat as you type with slashes being inserted around the letters and allow certain characters/numbers in whatever order/count you wish.

  • JasonB

    meioMask doesn’t work with textareas, only inputs.

  • JasonB

    meioMask doesn’t work with textareas, only inputs.

  • Paw

    meioMask is really nice, just too bad it dosn’t work with textarea…

  • Paw

    meioMask is really nice, just too bad it dosn’t work with textarea…

  • jim

    awesome. thanks, just saved me a bunch of time!

  • jim

    awesome. thanks, just saved me a bunch of time!

  • http://www.drupalargentina.com.ar Dario

    Thanks for this great tutorial. I just want to add my customization, I added the “bind” jquery function, then the count is updated if kepress or keydown. Sorry for my english.

    $(document).ready(function(){
    $(‘textarea[maxlength]‘).each(function() {
    var max = parseInt($(this).attr(‘maxlength’));
    $(this).after(“”);
    textareaMaxLength(this, max);
    $(‘textarea[maxlength]‘).bind(“keyup keydown”, function () { textareaMaxLength(this, max) });
    });
    });

    function textareaMaxLength(element, max) {
    var max = parseInt($(element).attr(‘maxlength’));
    if($(element).val().length > max){
    $(element).val($(element).val().substr(0, max));
    }
    $(element).parent().find(‘.charsRemaining’).html(‘Caracteres restantes: ‘ + (max – $(element).val().length));
    }

  • http://www.drupalargentina.com.ar Dario

    Thanks for this great tutorial. I just want to add my customization, I added the “bind” jquery function, then the count is updated if kepress or keydown. Sorry for my english.

    $(document).ready(function(){
    $(‘textarea[maxlength]‘).each(function() {
    var max = parseInt($(this).attr(‘maxlength’));
    $(this).after(“”);
    textareaMaxLength(this, max);
    $(‘textarea[maxlength]‘).bind(“keyup keydown”, function () { textareaMaxLength(this, max) });
    });
    });

    function textareaMaxLength(element, max) {
    var max = parseInt($(element).attr(‘maxlength’));
    if($(element).val().length > max){
    $(element).val($(element).val().substr(0, max));
    }
    $(element).parent().find(‘.charsRemaining’).html(‘Caracteres restantes: ‘ + (max – $(element).val().length));
    }

  • Sergy

    Hello Guys,
    How can i make it works for a unknown number of textareas added by the user. For me user can add a max number of textarea in a form using ajax. Now i want to limit the number of characters in each of the textarea and let the user see how many characters left in each of the textarea in the form.

    Please help
    Thanks

  • Sergy

    Hello Guys,
    How can i make it works for a unknown number of textareas added by the user. For me user can add a max number of textarea in a form using ajax. Now i want to limit the number of characters in each of the textarea and let the user see how many characters left in each of the textarea in the form.

    Please help
    Thanks

  • Matt

    Try http://pastebin.com/V9q3PPwJ

    Just pass the name of the textarea to limitTextarea().
    The textarea must have a maxlength attribute

  • Matt

    Try http://pastebin.com/V9q3PPwJ

    Just pass the name of the textarea to limitTextarea().
    The textarea must have a maxlength attribute

  • Teo

    Hi . great example. thanks a lot.
    I have 1 question:

    Suppose we have in a form a reset button and we have the following code:

    $(‘#reset’).click(function() {

    $(‘#menu_insert’)[ 0 ].reset();
    $(‘input#menu_title[maxlength]‘).parent().find(‘.charsRemaining’).html(‘You have ‘ + (max) + ‘ characters remaining’);

    });

    i am trying to reset also the output chars on the html. but that doesn’t work :/ any suggestions or work arounds ?

    THanks :)

  • Teo

    Hi . great example. thanks a lot.
    I have 1 question:

    Suppose we have in a form a reset button and we have the following code:

    $(‘#reset’).click(function() {

    $(‘#menu_insert’)[ 0 ].reset();
    $(‘input#menu_title[maxlength]‘).parent().find(‘.charsRemaining’).html(‘You have ‘ + (max) + ‘ characters remaining’);

    });

    i am trying to reset also the output chars on the html. but that doesn’t work :/ any suggestions or work arounds ?

    THanks :)

  • Dave

    Thanks for that script, it works great.

    I thought I’d try and make it automatically jump to the end of the scroll as my boxes are smaller in dimensions than their maxlength and was going to post the addition back here but I’m having trouble chaining after the shortening command so I’ve ended up leaving it, but it would be a nice feature to have if anyone knows off the top of their head how to do it.

  • Dave

    Thanks for that script, it works great.

    I thought I’d try and make it automatically jump to the end of the scroll as my boxes are smaller in dimensions than their maxlength and was going to post the addition back here but I’m having trouble chaining after the shortening command so I’ve ended up leaving it, but it would be a nice feature to have if anyone knows off the top of their head how to do it.

  • Conduit

    Dude. I’m absolutely happy with this code! Thank you!

  • Conduit

    Dude. I’m absolutely happy with this code! Thank you!

  • http://stackoverflow.com/users/300204/zaf zaf

    Hope you don’t mind me linking you from stackoverflowcom :

    http://stackoverflow.com/questions/2599688/textarea-maxlength-check

  • http://stackoverflow.com/users/300204/zaf zaf

    Hope you don’t mind me linking you from stackoverflowcom :

    http://stackoverflow.com/questions/2599688/textarea-maxlength-check

  • Raghu

    Hi,
    I am in love after seeing jquery. Nice snippet

  • Raghu

    Hi,
    Nice snippet. Really helpfull and usefull

  • Raghu

    Hi,
    I am in love after seeing jquery. Nice snippet

  • Raghu

    Hi,
    Nice snippet. Really helpfull and usefull

  • megatux

    If I use mouse to paste text, the validation does not occur :( , there is an onchange event or similar?

  • megatux

    If I use mouse to paste text, the validation does not occur :( , there is an onchange event or similar?

  • Bruno

    Helpfull and Usefull.
    On the line 5, you can replace $(this).attr(‘maxlength’) by max

    $(document).ready(function(){
    $(‘textarea[maxlength]‘).keyup(function(){
    var max = parseInt($(this).attr(’maxlength’));
    if($(this).val().length > max){
    $(this).val($(this).val().substr(0, $(this).attr(‘maxlength’)));
    }

    $(this).parent().find(‘.charsRemaining’).html(‘You have ‘ + (max – $(this).val().length) + ‘ characters remaining’);
    });
    });

    hugs

  • Bruno

    Helpfull and Usefull.
    On the line 5, you can replace $(this).attr(‘maxlength’) by max

    $(document).ready(function(){
    $(‘textarea[maxlength]‘).keyup(function(){
    var max = parseInt($(this).attr(’maxlength’));
    if($(this).val().length > max){
    $(this).val($(this).val().substr(0, $(this).attr(‘maxlength’)));
    }

    $(this).parent().find(‘.charsRemaining’).html(‘You have ‘ + (max – $(this).val().length) + ‘ characters remaining’);
    });
    });

    hugs

  • Matt

    Hi Bruno, thanks for pointing that out.

    There’s currently a better version of this script in jQuery plugin style, have a look in the post for the link.

  • Matt

    Hi Bruno, thanks for pointing that out.

    There’s currently a better version of this script in jQuery plugin style, have a look in the post for the link.

  • Matt

    Hi Bruno, thanks for pointing that out.

    There’s currently a better version of this script in jQuery plugin style, have a look in the post for the link.

  • http://twitter.com/alvincrespo Alvin Crespo

    This is nice, thanks for sharing!

  • Vbv

    bvb

  • http://twitter.com/mlerley Mike Lerley

    Cool! Thanks.

  • http://twitter.com/ahmadlafi Ahmad Lafi

    You are right, specially on IE :( (

  • http://zeeshanumardotnet.blogspot.com/ Zeeshan Umar

    It is really a simple and good solution. Thanks for sharing

  • http://www.phobu.com/ Tom

    Great little function, thanks for posting this!