Max Length Form Controls 2.0

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

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

Post a Comment

blog comments powered by Disqus

Random jQuery Plug-ins

  • Form to Link

    Run this plug-in on a form or an input[type=submit] and it will insert a link after the element you run it on which, on click, will submit said form.

    Details

  • Slide Presentation

    A sort of slide/presentation kind of plug-in. Displays sliding images with text floating on top. This one's pretty specific but perhaps someone will f...

    Details

  • View More

    This plug-in allows an element's contents to be hidden untill the user clicks a certain element. It works exactly like the HTML5 details and summary e...

    Details

More Plug-ins

Recent Comments

Powered by Disqus