Updated textarea maxlength with Jquery plugin

When I first wrote the “Textarea maxlength with jQuery” plugin last year I had no idea how popular it would be – over 70% of the visits to my site since then have been people reading that one post. The problem is, the code there is basically an ugly hack – you copy and paste and you’re done. But if you need to implement the same functionality across a site with slight differences to the functionality, you’d end up with a lot of copy and paste garbage. So what with it being time for some spring cleaning I thought I’d begin by refactoring the original code into a jquery plugin:

jQuery.fn.limitMaxlength = function(options){

	var settings = jQuery.extend({
		attribute: "maxlength",
		onLimit: function(){},
		onEdit: function(){}
	}, options);

	// Event handler to limit the textarea
	var onEdit = function(){
		var textarea = jQuery(this);
		var maxlength = parseInt(textarea.attr(settings.attribute));

		if(textarea.val().length > maxlength){
			textarea.val(textarea.val().substr(0, maxlength));

			// Call the onlimit handler within the scope of the textarea
			jQuery.proxy(settings.onLimit, this)();
		}

		// Call the onEdit handler within the scope of the textarea
		jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
	}

	this.each(onEdit);

	return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit)
				.live('input paste', onEdit);
}

And here’s an example of it in use, limiting all textareas in the document and updating a p element with the id of charsRemaining with… the number of characters remaining. It also sets the textarea bg color to red when the user tries to exceed the maxlength.

$(document).ready(function(){

	var onEditCallback = function(remaining){
		$(this).siblings('.charsRemaining').text("Characters remaining: " + remaining);

		if(remaining > 0){
			$(this).css('background-color', 'white');
		}
	}

	var onLimitCallback = function(){
		$(this).css('background-color', 'red');
	}

	$('textarea[maxlength]').limitMaxlength({
		onEdit: onEditCallback,
		onLimit: onLimitCallback
	});
});

And here’s a jsbin paste with a quick demo. Although there is a lot more code in this version it’s a lot more flexible as it allows you to decide how to inform the user of how many characters there’re remaining. It also means that it’ll take any characters already in the textbox into account when the document loads.

Update 2010/04/09: Fixed a few bugs & typos
Update 2010/08/01: Removed problematic comma & added live(‘input paste’) – thanks Surya and Len!

This entry was posted in Programming and tagged , , . Bookmark the permalink.
  • Pingback: Textarea maxlength with jQuery | That-Matt

  • http://rufact.org Len

    I think need to add “input paste” event:
    return this.keyup(onEdit)
    .keydown(onEdit)
    .focus(onEdit)
    .live(‘input paste’, onEdit);

  • http://rufact.org Len

    I think need to add “input paste” event:
    return this.keyup(onEdit)
    .keydown(onEdit)
    .focus(onEdit)
    .live(‘input paste’, onEdit);

  • http://magicbg.com miga

    Hi,
    Тhis one is the best implementation which I found on the net.
    Thanks for sharing.

  • http://magicbg.com miga

    Hi,
    Тhis one is the best implementation which I found on the net.
    Thanks for sharing.

  • http://eng-corp.com/blog gerg

    I like this plugin implementation. Thank you!

  • http://eng-corp.com/blog gerg

    I like this plugin implementation. Thank you!

  • giga718

    super!!!!!! Thanks you!

  • giga718

    super!!!!!! Thanks you!

  • Preston

    A user can get around the maximum length by entering the following in the address bar for most modern browsers:

    javascript:void($(‘textarea’).each(function(){$(this).attr(‘maxlength’,’1200′);}))

    That sets the maximum length to 1200 characters. I’m trying to think of an efficient way to prevent this. Any ideas?

    Thanks,

    - Preston

    • Andy

      There may be a way to prevent this client-side, but I’d think it’d be less of a headache to just handle it server-side (e.g., make sure the text length doesn’t exceed the maximum length of the database field you’re inserting it into), which is something you’ll probably want to be doing anyway.

  • Preston

    A user can get around the maximum length by entering the following in the address bar for most modern browsers:

    javascript:void($(‘textarea’).each(function(){$(this).attr(‘maxlength’,’1200′);}))

    That sets the maximum length to 1200 characters. I’m trying to think of an efficient way to prevent this. Any ideas?

    Thanks,

    - Preston

  • Matt

    If someone wanted to they could just disable javascript and not be bothered by any of the warnings; this (and every other js validation plugin) is just a minor deterrent – pure ui candy.

    It’s assumed that you have some kind of script on the backend which validates your user input to make sure that it doesn’t exceed a certain length.

  • Matt

    If someone wanted to they could just disable javascript and not be bothered by any of the warnings; this (and every other js validation plugin) is just a minor deterrent – pure ui candy.

    It’s assumed that you have some kind of script on the backend which validates your user input to make sure that it doesn’t exceed a certain length.

  • silmarilon

    awesome! thank you for post.

  • silmarilon

    awesome! thank you for post.

  • surya

    IE6 was giving error “expected identifier string or number”. Thats gfixed after removing the last comma.
    i.e.
    $(‘textarea[maxlength]‘).limitMaxlength({
    onEdit: onEditCallback,
    onLimit: onLimitCallback
    });

  • surya

    IE6 was giving error “expected identifier string or number”. Thats gfixed after removing the last comma.
    i.e.
    $(‘textarea[maxlength]‘).limitMaxlength({
    onEdit: onEditCallback,
    onLimit: onLimitCallback
    });

  • Matt

    Updated, thanks Len & surya!

  • Matt

    Updated, thanks Len & surya!

  • Keith

    Great little snippet, Thanks.

    I just do a forced trim on the server side, to stop anyone who is determined to bypass the maxlength feature.

  • angel

    This does not work when copy – right click paste

  • Chad

    Can’t you just return false from the keydown event handler if the text length is longer than the max? This will consume the event and you won’t see characters flicker like you do with the method that resets the value of the textarea. i.e.

    $(‘#myTextArea’).keydown(function() {
    if($(this).val().length > maxLength) {
    return false;
    }
    });

  • asahi

    Bonjour de la France.

    Solution for the 1 byte/2 bytes problèm with the newline on a textarea
    added : lineFeeds that is substracted to the length
    sorry for my english

    var onEdit = function()
    {
    var textarea = jQuery(this);
    var maxlength = parseInt(textarea.attr(settings.attribute));
    var lineFeeds = textarea.val().match(/[^n]*n[^n]*/gi).length;

    if(textarea.val().length > maxlength-lineFeeds)
    {

    textarea.val(textarea.val().substr(0, maxlength-lineFeeds));

    // Call the onlimit handler within the scope of the textarea
    jQuery.proxy(settings.onLimit, this)();
    }

    // Call the onEdit handler within the scope of the textarea
    jQuery.proxy(settings.onEdit, this)(maxlength-lineFeeds – textarea.val().length);
    }

    • tomc

      Thanks for posting this, it helps with cross-browser behaviour. However I did have to add a check to see if ‘textarea.val().match(/[^n]*n[^n]*/gi)’ returns null – it will be null (in FF4 at least) when the textarea does not contain any text e.g. on first use.

    • lmeurs

      Isn’t this awkward?

      var lineFeeds = textarea.val().match(/[^n]*n[^n]*/gi).length; 

      You are (case insensitively) searching for:

      1) zero or more 
      non-newlines, 
      2) a 
      newline  and 
      3) then again  zero or more non-newlines.

      My quess is that ***any*** newline will match this regex, independently of  what preceding/succeeding characters.

  • Meiling

    Very Nice! Thx!

  • todd

    On the server side a return is being counted as 2 characters while in this script it’s counted as only one. Trying to figure out how to get around this via javascript/jquery. Thoughts?

  • Markus

    How about using events to notificate about changes?

    $(this).trigger(‘charlimit’, maxLength); // When limit reached
    $(this).trigger(‘charremaining’, maxLength – $(this).val().length); // Always

    And then:
    $(‘textarea[maxlength]‘).bind(charremaining, function(event, remaining) {
    $(this).siblings(‘.charsRemaining’).text(“Characters remaining: ” + remaining);
    )};
    // and
    $(‘textarea[maxlength]‘).bind(charlimit, function() {
    $(this).css(‘background-color’, ‘red’);
    )};

  • http://twitter.com/tobiasly Toby J

    Thanks for the code! I believe you meant to say, “updating a p element with the *class* of charsRemaining”, not the *id* of charsRemaining.

  • Guest1024

    On what license are you realeasing this code? Please make it something like jQuery’s so we can use it.

    Thanks

  • Pingback: jQuery script to handle textarea maxlength - Anil Natha [dot] com

  • http://profiles.google.com/zxdong ZHAO Xudong

    thank you,i googled ,this is what i want.

  • http://maffooclock.myopenid.com/ Matthew Clark

    This appears to not work in IE 8 (and below, perhaps).  I’ve started at the code and made a few tweaks, but nothing helps.  I don’t get any errors, though.

  • Abdulla Al NUAIMI
  • Ali Amaan
  • Johnnie

    the onLimit only seem to work in IE?

  • Nico VanHaaster

    Simple Yet Effective!

  • Bruce

    When the field contains the maximum number of characters, I can type in the middle of the field and I lose the text at the end of the field.  Any idea of how to prevent this?

  • Ron Del Rosario

    Thanks for the great plugin. It was just what I needed! :D

  • http://www.elrinth.com/ Nicklas Holmgren

    Getting sometimes NaN on the chars remaining. And it stays that way afterwards even after deleting chars… Any clue why?

  • Pinsonbavard

    i like this

  • Gabriel

    Works great! Thanks a lot