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.
  • http://sigswitch.com/2008/07/textarea-maxlength-with-jquery/ Textarea maxlength with jQuery | That-Matt

    [...] There’s an updated version of this script here [...]

  • 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

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

blog comments powered by Disqus