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.

Kommentarer

Bild för Anders

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.

Bild för Emil

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

Bild för Tim Beadle

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

Bild för alexx

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 :)

Bild för Lucifix

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

Bild för muky

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

Bild för Oskar Rough

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?

Bild för Emil

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

Bild för Emil

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

Bild för Gäst

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!

Bild för Gäst

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

Bild för Emil

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.

Bild för Bas

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.

Bild för Mark

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

Bild för Bernd

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

Bild för Gäst

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

blur works as well.

Bild för Snorri

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.

Bild för Emil

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

Bild för kevin

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;
}
Bild för Emil

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

Bild för BASTA!

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!

Bild för Gäst

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

Bild för Jez

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

Bild för Emil

@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?

Bild för Jez

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

Bild för Ted

Hi Emli,

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

Bild för Emil

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

Bild för Soben

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 :)

Bild för Emil

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

Bild för Anthony

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.

Bild för Anthony

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.

Bild för Anthony

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

Bild för Hyoseong Choi

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.

Bild för jesus

Muchas gracias es lo que estaba buscando

Bild för Ramón Parra Campos

Perfecto, mil gracias.

Bild för Jan-Michael Hoofdmann

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.

Bild för pats

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.

Bild för mtc

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??

Bild för Rohith Gopi

When pasting it is accepting the input.

Lägg till ny kommentar