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(0, maxLength));
}
charRemaining.text((maxLength - t.val().length) + ' ' + config.remainingStr);
});
});
});
};
Random jQuery Plug-ins
Center
This little pluggy centers an element on the screen using either fixed or absolute positioning. Can be used to display messages, pop up images etc.
Vibrate
This plug-in makes any element you want "vibrate" every now and then. Can be used in conjunction with blink for maximum annoyance!
Code Block Toolbar
If you post code-examples on your site you can use this plug-in to add some nifty buttons below each code-example that allows the user to, for example...