/ Published in: jQuery
A little snippet that visualizes the \"maxlength\" attribute, used on the HTML \"input\" and \"textarea\" elements.\r\n\r\nThe snippet is set up in such a way as to give you easy control over...\r\n\r\n1. formatting of the counter\r\n2. the HTML tag where the counter is put\r\n3. where in the document you want the counter to be displayed\r\n\r\nThe snippet is quite self-explanatory, but I have commented on basically everything. Read the comments for further help.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
$(document).ready(function() { // Targets all form elements that have the "maxlength" attribute and visualizes // the interaction with them by counting up to the maximum allowed characters. $("[maxlength]").each(function(){ // The format of the counter. {num} is the number that changes when the user // uses the keyboard, and {max} is the "maxlength" attribute. You can put // HTML tags into the formatting if you want. var format = '({num} out of {max})'; // The counter. Default is a <span> tag. You can do whatever you like with it, // such as add a class name, add CSS or even animate it. The formatted text // (fomat above) will be put into the tag itself. var counter = $('<span />').addClass("maxlengthdisplay"); // Set where the counter should be shown. You can place it wherever you like. // Default is right after the input or textarea. $(this).after( counter ); // Get the "maxlength" attribute and turn it into an integer (whole number). var max = parseInt($(this).attr("maxlength"),10); // If "max" (ie. "maxlength") is less than 1 or not a number then abort. if (max<1 || typeof max!="number"){ counter.remove(); return; } // Using the formatting we have set, prepare the counter. counter.html(format.replace("{num}",$(this).val().length).replace("{max}",max)); // Every time the user touches the keyboard... $(this).keyup(function(){ // ...count how many characters are in the input or textarea. var len = $(this).val().length; // ...and update the counter accordingly. counter.html( format.replace("{num}",len).replace("{max}",max) ); }); // That is it. }); });