Max Length Form Controls 2.0

Created Sunday 31st of August 2008 by Andreas Lagerkvist
Copyright © 2008 Andreas Lagerkvist (andreaslagerkvist.com)

Please have a look at the "Other Resources" for bug reports or further help on jQuery. Do not post bug reports or feature requests as comments to unrelated articles. If bug reporting on bugtracker.a-framework.org fails, e-mail me.

What it Does

Gives form-controls with a 'maxlength-XXX'-class a max-length and prohibits user from entering more than set amount. It also displays number of characters user has left next to the control.

How to Use

jQuery(document.body).maxLengthFormControls();

Run the plug-in on a parent-element of the form-controls.

Example

Example Code

HTML

<div id="jquery-max-length-form-controls-example">
<
p>
    <
label>
        
Dummy<br />
        <
input type="text" name="dummy" class="maxlength-8" />
    </
label>
</
p>
</
div>

JS

// I already use it on my site...
// jQuery(document.body).maxLengthFormControls();

Source Code

jQuery.fn.maxLengthFormControls = function (conf) {
    var 
config jQuery.extend({
        
remainingStr:    'remaining'
        
className:        'characters-remaining'
    
}, conf);

    return 
this.each(function () {
        
jQuery('*[class*="maxlength-"]'this).each(function () {
            var 
t                = $(this);
            var 
maxLength        parseInt(t.attr('class').replace(/.*?maxlength-([0-9]+)/, '$1'), 10);
            var 
remaining        maxLength t.val().length;
            var 
charRemaining    jQuery('<span class="' config.className '">' remaining ' ' config.remainingStr '</span>').insertAfter(t);

            
t.keyup(function () {
                if (
t.val().length maxLength) {
                    
t.val(t.val().substring(0maxLength));
                }

                
charRemaining.text((maxLength t.val().length) + ' ' config.remainingStr);
            });
        });
    });
};

Download

Plug-in

Requires

Random jQuery Plug-ins

  • Vibrate

    This plug-in makes any element you want "vibrate" every now and then. Can be used in conjunction with blink for maximum annoyance!

    Details

  • Image Zoom

    This plug-in makes links pointing to images open in the "Image Zoom". Clicking a link will zoom out the clicked image to its target-image. Click anywh...

    Details

  • Checked checkbox-parent

    This tiny plug-in adds and removes a 'checked'-class to input[type=checkbox]'s parents. Very useful if you want to style the entire wrapping <label>-e...

    Details

More Plug-ins

Recent Comments

  1. Andreas on "SleekPHP User Handling"

    Thank you for showing interest :) Were the docs en...

  2. ciptard on "SleekPHP User Handling"

    Ok, thank you

  3. Andreas on "SleekPHP User Handling"

    I might write a "getting started" article for Slee...