Maxlength with jQuery

In this tutorial I will show you how to use jquery.maxlength.js on some common form fields

To start, you will need to download a copy of the jQuery library http://docs.jquery.com/Downloading_jQuery.
This plugin works with both 1.2.6 and 1.3.X
You will also have to download the plugin jquery.maxlength.js

When you have downloaded the copy you will need to include it in your file.

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
  </head>
<body>
  <!-- we will add our HTML content here -->
</body>
</html>

Next step is to include jquery.maxlength.js

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="jquery.maxlength-min.js"></script>
  </head>
<body>  
  <!-- we will add our HTML content here -->
</body>
</html>

Now to the fun part, how to apply the functionality to your script.

Plugin options

<script type="text/javascript">
$(document).ready(function(){    
  $('#textarea_1_1').maxlength({   
    events: [], // Array of events to be triggerd    
    maxCharacters: 10, // Characters limit   
    status: true, // True to show status indicator bewlow the element    
    statusClass: "status", // The class on the status div  
    statusText: "character left", // The status text  
    notificationClass: "notification",	// Will be added when maxlength is reached  
    showAlert: false, // True to show a regular alert message    
    alertText: "You have typed too many characters.", // Text in alert message   
    slider: false // True Use counter slider    
  }); 
});
</script>

Textarea

To use this on a simple textarea

<script type="text/javascript"> 
  $(document).ready(function(){   
    $('#textarea_1_1').maxlength(); 
  });
</script>

To use this on multiple textareas

To use this on multiple textareas

<script type="text/javascript">
  $(document).ready(function(){  
    $('div.example2 textarea').maxlength(); 
  });
</script>

Textareas

To use this on multiple textareas, with diffrent settings

This textarea has no status indicator, but it has an alert notification

<script type="text/javascript">
  $(document).ready(function(){
    $('div.example3 textarea').maxlength();	
    $('#textarea_3_2').maxlength( {status: false, showAlert: true} );  
  });
</script>

Textareas with triggers

To use trigger your own events (new in 1.0.2)
('keyup' is default and cant be changed)

<script type="text/javascript">
  $(document).ready(function(){
    $('div.example4 textarea').maxlength();	
    $('#textarea_4_1').maxlength( {events: ['blur']} );  
  });
</script>

Textareas with slide counter

To use slider counter on one ot many elements (new in 1.0.3)

 

<script type="text/javascript">
  $(document).ready(function(){
    $('div.example5 textarea, div.example5 input').maxlength( {slider: true} ); 
  });
</script>

Changelog

jquery.maxlength.js 1.0.5 (released 2009-05-16)
  • Fixed: Wrong div got deleted when the status was deleted (Thanks hiyer for the solution)
jquery.maxlength.js 1.0.4 (released 2009-05-13)
  • Fixed: Comma problem in IE (Thanks muky)
  • Fixed: Now it runs through jslint.com without errors
jquery.maxlength.js 1.0.3 (released 2009-03-13)
  • Added: Support for slider divs (Thanks Michael Maass)
jquery.maxlength.js 1.0.2 (released 2009-02-07)
  • Added: Support for userdefined events
  • Added: Support for jQuery 1.3.1
  • Added: Some more comments
  • Added: Version in the filename
  • Fixed: Some misspellings (Thanks monk.e.boy)

Author and license

Emil Stjerneman
Dual licensed under the MIT or GPL Version 2 licenses.

Comments

Anders's picture
Anders
18 March 2009 - 15:35

Funktionen skär bort överstigande tecken så att de blir tio men arean är fortfarande röd. Förslag: rödmarkeringen gäller vid maxlängd +1.

emil's picture
emil
19 March 2009 - 00:21

Ja det har du faktiskt rätt i. Fast maxlängd +1 funkar ju inte att köra på då syftet är just att limitera till X (maxlängd) antal tecken. Får klura på denna

Tim Beadle's picture
Tim Beadle
30 April 2009 - 15:01

Hi, I've run your script through jslint.com and fixed some errors (one of which was causing errors in IE6 & 7).

Please email me on the supplied address if you'd like me to send the modified version.

Regards, Tim

alexx's picture
alexx
03 May 2009 - 22:42

hello,

your code doesnt resolve problem with pasting from clipboard.
put some text in clipboard and press Ctrl+V in these textarea - counter isnt working :)

Lucifix's picture
04 May 2009 - 18:51

Can you please tell me how to show how many characters are left before textarea?

muky's picture
muky
05 May 2009 - 12:21

Version 1.0.3 has a bug that occurs only in IE.
the presence of a comma (,) is a bug in IE. This is a very popular bug :)

Just change line 24
slider: false, // Use counter slider
to
slider: false // Use counter slider

Oskar Rough's picture
Oskar Rough
05 May 2009 - 15:52

Thank you. It's working nicely, however I've got one problem.

Say I've written the following:

[img]test[/img]

This will result in 5+4+6 = 15 chars. I only want it to count the 4 chars. Same goes when creating links etc, etc. I assume this is some regular expressions, or?

emil's picture
emil
13 May 2009 - 21:51

@alexx: No , thats true. I have no solution for that, if you have one and you would like to share that, feel welcome to email me.

@Lucifix: To do that, just change all ".next(" to ".prev(" (its about 5) and also change "after" to "before" at line 52.

emil's picture
emil
13 May 2009 - 22:03

@Oskar Rough: Yes, that would be possible with regular expressions. I will take a look at this ans see what I can do.

Gäst's picture
Gäst
02 June 2009 - 11:37

Can it be made so that one can pass in a method pointer when the input field content has exeeded the limit? (I'd like to disable the submit button when that happens)

Other than that I really like this script. Kudos!

Gäst's picture
Gäst
05 June 2009 - 12:51

This plugin not support drag-and-drop text into control.

emil's picture
emil
10 June 2009 - 00:42

I think I understand what you saying about the "pointer". I will take a look at this and see what I can do.

@This plugin not support drag-and-drop text into control.
No sorry, It does not. If you have any suggestions on how to solve that, feel free to email me.

Bas's picture
Bas
14 July 2009 - 10:07

It would really help if you mentioned somewhere in this documentation how to specifiy the max amount of characters. It defaults to 10 chars, but you don't mention how to change this value :) I had to look in your code to find out that there is a "maxCharacters:" setting.

Mark's picture
Mark
15 August 2009 - 17:45

As Bas said, nowhere on this page is the most crucial information, setting the limit of characters.

For anyone interested, here is the javascript call for 135 chars
$('#content').maxlength({maxCharacters:135});

Looking through the un-minimized js will also give info on the other available options.

Great plugin, cheers - just a little lacking in documentation

Bernd's picture
Bernd
24 August 2009 - 12:05

Complete options: 

- events: array
ex.: ['onFocus'] - resolves the problem with pasting from clipboard
- maxCharacters: int
ex.: 135 - max. of 135 chars
- status: bool
ex.: false - disables the chars left message
- statusClass: string
ex.: 'myStatusCssClass' - own CSS class for the status message
- statusText: string
ex.: 'Zeichen übrig' - for localization of status message
- notificationClass: string
ex.: 'myNotificationCssClass' - own CSS class to be binded to the textarea/input field if max chars exceeded
- showAlert: bool
ex.: true - shows a javascript alert box
- alertText: string
ex.: 'Du hast zu viele Zeichen eingegeben' - for localization of the JS alert box
- slider: bool
ex.: true - slide in/out the status message

 

Gäst's picture
Gäst
02 September 2009 - 07:05

to solve drag-drop : add change event
events: ['change']

blur works as well.

Snorri's picture
Snorri
03 September 2009 - 16:03

I noticed a but with the textarea that uses alert box, you can't get rid of the alert box, just pops up again and again and again becase the text in the textarea if over the limit.

emil's picture
emil
29 September 2009 - 00:37

Now I have added an option section in this article with all the plugin params. Hope this will easyer to understand.

kevin's picture
kevin
10 October 2009 - 05:48

replacing lines 29 and 30 with the following will read the 'maxlength' attribute from the source element, if present, and use that instead of having to specify the 'maxCharacters' in the options.

var item = $(this);
var charactersLength = item.val().length;

var maxlengthAttr = item.attr('maxlength');
if (maxlengthAttr) {
    settings.maxCharacters = maxlengthAttr;
}
emil's picture
emil
18 October 2009 - 20:56

@Kevin Thats a grate Idea for input texts, but "maxlength" attribute is not valid for textareas.

BASTA!'s picture
BASTA!
13 November 2009 - 05:14

Funny thing, I've seen literally dozens of plugins for enforcing maxlength on a textarea, and ALL of them, including yours, suffer from the same weakness: if you exceed the imposed maxlength while typing somewhere **in the middle** of the control, then the *last* character in the control is deleted instead of the one you just typed.

The Holy Grail is:

1) prevent content from exceeding maximum length
2) if characters need to be discarded:
* discard characters from the end of *added* text, not from the end of content
* if multiple characters are pasted, the final state of the control must be the same as if the text were typed one character at a time. By state I mean content, caret position, and scroll position.

The problem mostly reduces to getting and setting caret position in a textarea reliably across browsers. It is a hellishly difficult task!

Gäst's picture
Gäst
25 December 2009 - 21:06

Denna plugin är riktigt bra. Tack för att du gjorde det.

Jez's picture
Jez
03 February 2010 - 12:23

Hi, this plugin is excellent.

I would make one change however - The notification class should replace the status class when the max length is reached (i.e. restyling the status div).

emil's picture
emil
03 February 2010 - 23:23

@Jez, Thanks for appreciating my plugin. Good idea, but I dont think I will make that change. It is too hard to make it backwards compatible for all the users. Please feel free to modify and use it as you like. You need help with that change?

Jez's picture
Jez
04 February 2010 - 18:55

@Emil, thanks but I have decided to simply not use that class at all.

Ted's picture
15 February 2010 - 10:20

Hi Emli,

the plugin doesn't work with copy and paste. How can I prevent that?

emil's picture
emil
15 February 2010 - 19:20

@Ted: Unfortunately I know that, and I dont have any suggestions on how to solve that. Feel free to post if you have any.

Soben's picture
22 April 2010 - 22:34

Emil, instead of doing a keyup, why not do something more like an on blur event? Perhaps that will solve the copy and paste, in some way? This is just from the top of my head, so I'm not positive at all :)

emil's picture
emil
23 April 2010 - 13:06

@Soben Its possible for any users to attach their own events like blur and so on.
$('selector').maxlength( {events: ['blur','click',.....]} );

Anthony's picture
Anthony
14 March 2011 - 15:51

Do you have a solution for the ENTER key? Press ENTER once in your textbox. The plugin will show that you have only used 1 character. However, when you submit the form, asp.net shows that the string has a length of 2.

Anthony's picture
Anthony
14 March 2011 - 17:11

It looks like it has to do with the way the val().length works in jQuery. val().length will return one character if you have an ENTER, however, .value.length will return 2.

Anthony's picture
Anthony
14 March 2011 - 17:31

IE sees ENTER as both LINE-FEED and CARRIAGE-RETURN. Firefox sees it as just LINE-FEED. This is just a browser issue that we will have to deal with. Thanks to the following page for info about LINE FEED and CARRIAGE RETURN: http://www.maxi-pedia.com/Line+termination+line+feed+versus+carriage+ret...

Hyoseong Choi's picture
Hyoseong Choi
10 April 2011 - 03:53

what about multibyte characters? Korean, Chinese, Japanese... It recognize two-byte one character as one byte... It is natural that it should recognize two-byte chanracter as two bytes.

jesus's picture
18 June 2011 - 05:20

Muchas gracias es lo que estaba buscando

Ramón Parra Campos's picture
Ramón Parra Campos
21 September 2011 - 18:06

Perfecto, mil gracias.

Jan-Michael Hoofdmann's picture
Jan-Michael Hoo...
06 November 2011 - 15:48

Hello, I wanted to use this script in combination with the jquery validation plugin. My problem was, that the wrong element was used. So I changed two pieces of the code like this:

function D() {
var K = C.maxCharacters - J;
if(K < 0) {
K = 0
}
G.nextAll("div." + C.statusClass + ":first").html(K + " " + C.statusText)
}

if(C.slider) {
G.next("div." + C.statusClass).hide();
G.focus(function() {
G.nextAll("div." + C.statusClass + ":first").slideDown("fast");
});
G.blur(function() {
G.nextAll("div." + C.statusClass + ":first").slideUp("fast");
})
}

The nextAll function is a little bit slower than the next function, but in this case I think the best choice.

pats's picture
pats
11 April 2012 - 16:57

Can you update this plugin to support double byte characters like IME content for Japanese or Chinese etc. I tested this demo web page with Japanese keyboard, and there are issues. For example, if user keeps typing text larger than given max length then the plugin deletes extra characters but somehow also replaces the characters within the boundary.

mtc's picture
mtc
03 April 2013 - 14:17

Hi all...
Very Good Code with User Friendly UI.
The only Problem is that this code is not working with the pages that have Master Pages.
Status Dive is not appearing there. Any solutions??

Rohith Gopi's picture
Rohith Gopi
22 April 2013 - 15:02

When pasting it is accepting the input.

aloha's picture
aloha
30 August 2013 - 11:27

”if user keeps typing text larger than given max length then the plugin deletes extra characters but somehow also replaces the characters within the boundary.”
=>I am having this problem with IE. Did you fix it?

Gopal Aggarwal's picture
29 October 2013 - 07:55

Thank you.

Anita K.'s picture
Anita K.
03 March 2014 - 14:02

I use JSF 2.0. If the page is loaded, and textarea got focus, then everything is ok, the indicator text of remaining characters is shown. But I have a <h:selectOneMenu> too, and if the user selects some text from this dropdown, I want to refresh my textarea. This is my code:

<h:selectOneMenu value="#{member.phoneComment}" >
  <f:selectItems value="#{code.phoneComments}" var="_code" itemValue="#{_code.text}" itemLabel="#{_code.text}" />
  <f:ajax event="change" execute="@this" render="phonecomments"/>
</h:selectOneMenu>
<h:inputTextarea id="phonecomments" rows="4" cols="17" value="#{member.selected.phoneComments}" />

And the problem is when I rerender the textarea, the maxlength library does not working, I click in the textarea, but it doesn't show the remaining characters, and it seems that the ajax render removes the maxlength library. Does anyone has any idea what happens in this case?

emil's picture
emil
10 March 2014 - 10:04

You probably what to add some other event to the event options.

Guna's picture
Guna
13 March 2014 - 22:13

Can any please help me how to limit number of lines in the textarea?

Rob Combs's picture
Rob Combs
17 June 2014 - 10:50

hi, i've updated the plug in to allow for delegation so that current and future text fields will be processed.

/**
* jQuery Maxlength plugin
* @author Emil Stjerneman, updated by Rob Combs
* @version $Id: jquery.maxlength.js 18 2014-06-17
* @package jQuery maxlength 1.0
*/

(function($) {
$.fn.maxlength = function(options) {
/* jQuery plugin that enforces a max length on text elements. This plugin also supports event delegation to bind
events to existing and future objects created in the DOM.

Example usage:
$('textarea.vLargeTextField').maxlength({
events: [], // Array of events to be triggered
maxCharacters: 110, // Characters limit
status: true, // True to show status indicator below the element
statusClass: "status", // The class on the status div
statusText: "characters left", // The status text
notificationClass: "max-length-notification", // Will be added when maxlength is reached
showAlert: false, // True to show a regular alert message
alertText: "You have typed too many characters.", // Text in alert message
slider: false // True Use counter slider
});

*/
var settings = jQuery.extend(
{
events: [], // Array of events to be triggerd
maxCharacters: 10, // Characters limit
status: true, // True to show status indicator bewlow the element
statusClass: "status", // The class on the status div
statusText: "characters left", // The status text
notificationClass: "notification", // Will be added to the emement when maxlength is reached
showAlert: false, // True to show a regular alert message
alertText: "You have typed too many characters.", // Text in the alert message
slider: false // Use counter slider
}, options );

// Add the default event
$.merge(settings.events, ['keyup']);

// Update status div
function updateStatus(obj) {
var charactersLeft = settings.maxCharacters - $(obj).val().length;
if(charactersLeft < 0) {
charactersLeft = 0;
}
obj.next("div").html(charactersLeft + " " + settings.statusText);
}

// check the number of characters compared to settings.maxCharacters
function checkChars(obj) {
var valid = true;
// Too many chars?
if($(obj).val().length >= settings.maxCharacters) {
// Too may chars, set the valid boolean to false
valid = false;
// Add the notifycation class when we have too many chars
obj.addClass(settings.notificationClass);
// Cut down the string
obj.val(item.val().substr(0,settings.maxCharacters));
// Show the alert dialog box, if its set to true
showAlert();
} else {
// Remove the notification class
if(obj.hasClass(settings.notificationClass)) {
obj.removeClass(settings.notificationClass);
}
}

if(settings.status) {
updateStatus(obj);
}
}

// Shows an alert msg
function showAlert() {
if(settings.showAlert) {
alert(settings.alertText);
}
}

// Check if the element is valid
function validateElement(obj) {
var ret = false;
if(obj.is('textarea')) {
ret = true;
} else if(item.filter("input[type=text]")) {
ret = true;
} else if(item.filter("input[type=password]")) {
ret = true;
}
return ret;
}

// Bind events to the text elements to trigger max length updates
$.each(settings.events, function(i, n){
$("body").delegate($(this).selector, n, function (e) {
item = $(e.target)
charactersLength = $(item).val().length;
checkChars($(item));
});
});

return this.each(function() {
var item = $(this);
var charactersLength = $(this).val().length;

// Validate
if(!validateElement($(item))) {
return false;
}

// Insert the status div
if(settings.status) {
item.after($("").addClass(settings.statusClass).html('-'));
updateStatus($(item));
}

// Remove the status div
if(!settings.status) {
var removeThisDiv = item.next("div."+settings.statusClass);
if(removeThisDiv) {
removeThisDiv.remove();
}
}

// Slide counter
if(settings.slider) {
item.next().hide();
item.focus(function() {
item.next().slideDown('fast');
});
item.blur(function() {
item.next().slideUp('fast');
});
}
}); // end this.each(function()
}; // end $.fn.maxlength
})(django.jQuery); // end max length jquery plug in

Rob Combs's picture
Rob Combs
17 June 2014 - 10:53

doesn't look like I can edit the previous post so here is a formatted gist of code that I've posted: https://gist.github.com/RobCombs/60ec6dbca72bb7b68ed9

Michael's picture
Michael
06 August 2014 - 08:44

This doesn't work with .net

emil's picture
emil
11 August 2014 - 05:03

Why shouldn't it work? It's JavaScript.

Sheryl's picture
Sheryl
07 September 2014 - 12:30

Je pensе que j'en parlerai surr սn site internet perso

Also visit my weƄite ... partouze hardcore

Add comment