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://twitter.com/alvincrespo Alvin Crespo

    This is nice, thanks for sharing!

  • Vbv

    bvb

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

    Cool! Thanks.

  • 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!

  • Ramaraju256

    When u click enter its not giving correct result

  • anonymous

    What about pasting to textarea? Does your example work for this case?