Cut & Paste jQuery MaxLength for INPUT and TEXTAREA fields
|
Description: This useful form validation script
lets you add a custom "maxlength" attribute to INPUT type="text"
and TEXTAREA
elements, so users are prevented from entering more
characters into these fields than the designated number. Inspired by
Twitter's input box, it can
optionally show the number of characters remaining for a field as the user types
while displaying this info in different colors depending on how close the user
is to the limit.
Recall that HTML supports a maxlength
attribute by
default, although it only applies to INPUT elements, and furthermore, cannot
show the user the number of characters remaining.
Example:
Directions
Step 1: Add the following script to the <HEAD> section of your page:
Be sure to download maxlength.js (right click and select "Save As"), the external file referenced by the above code.
Step 2: Then, add the below sample form to your <BODY>:
As illustrated inside the form, you insert the following two attributes into a INPUT or TEXTAREA element to limit its size:
-
data-maxsize
: Define this attribute with an integer value to set the maximum number of characters the field will accept. -
data-output
: If you wish to display in real time the # of characters remaining, define this attribute and set it to the ID of a blank container (ie: a DIV or SPAN) on the page that will show this info.
Dynamically applying "maxlength" to a form field
Instead of manually adding the aforementioned two attributes to your static form fields, you can also dynamically apply a "maxlength" to a field, such as one that's dynamically created. Simply call the function:
setformfieldsize($field, maxsize, outputfieldid)
Where the following 3 parameters are accepted:
-
$field
: Reference to the form field(s) you wish to apply "maxlength" to, as jQuery objects! So for example, to reference the form field with ID "myname", the value to enter would bejQuery('#myname')
. See the jQuery Documentation page for more info. -
maxsize
: An integer value specifying the maximum number of characters the field should accept. -
outputfieldid
: If you wish to display in real time the # of characters remaining, enter the ID of a blank container (ie: a DIV or SPAN) on the page that should show this info.
Here's an example:
jQuery(document).ready(function($){ //fire on DOM ready setformfieldsize(jQuery('#comment'), 50, 'charsremain') })