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)

BilagaStorlek
jquery.maxlength.js.txt3.56 kB
jquery.maxlength-min.js.txt1.5 kB
maxlength.zip30.74 kB

Kommentarer

Skriv kommentar
Gästs bild
Anders
18 mars, 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.

#1
Emils bild
Emil
19 mars, 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

#2
Gästs bild
Tim Beadle
30 april, 2009 - 14: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

#3
Gästs bild
alexx
3 maj, 2009 - 21: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 :)

#4
Gästs bild
Lucifix
4 maj, 2009 - 17:51

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

#5
Gästs bild
muky
5 maj, 2009 - 11: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

#6
Gästs bild
Oskar Rough
5 maj, 2009 - 14: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?

#7
Emils bild
Emil
13 maj, 2009 - 20: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.

#8
Emils bild
Emil
13 maj, 2009 - 21:03

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

#9
Gästs bild
Gäst
2 juni, 2009 - 10: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!

#10
Gästs bild
Gäst
5 juni, 2009 - 11:51

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

#11
Emils bild
Emil
9 juni, 2009 - 23: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.

#12
Gästs bild
Bas
14 juli, 2009 - 09: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.

#13
Gästs bild
Mark
15 augusti, 2009 - 16: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

#14
Gästs bild
Bernd
24 augusti, 2009 - 11: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

#15
Gästs bild
Gäst
2 september, 2009 - 06:05

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

blur works as well.

#16
Gästs bild
Snorri
3 september, 2009 - 15: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.

#17
Emils bild
Emil
28 september, 2009 - 23:37

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

#18
Gästs bild
kevin
10 oktober, 2009 - 04: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;
}

#19
Emils bild
Emil
18 oktober, 2009 - 19:56

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

#20
Gästs bild
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!

#21
Gästs bild
Gäst
25 december, 2009 - 21:06

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

#22
Gästs bild
Jez
3 februari, 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).

#23
Emils bild
Emil
3 februari, 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?

#24
Gästs bild
Jez
4 februari, 2010 - 18:55

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

#25
Gästs bild
Ted
15 februari, 2010 - 10:20

Hi Emli,

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

#26
Emils bild
Emil
15 februari, 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.

#27

Skriv ny kommentar

Visar din Gravatar ikon