Input & Textarea Character Limit Display with jQuery

2014-09-21 • Snippets • Views: 1427

Input & Textarea Character Limit Display with jQuery

[php]

/*
This little jQuery snippet will let you quickly add a limit counter
to input fields to display available remaining characters.
A nice feature to include for improved user experience.
Source: http://www.scriptiny.com/2012/09/jquery-input-textarea-limiter/
Demo: http://sandbox.scriptiny.com/tinylimiter/
*/

function($) {
$.fn.extend( {
limiter: function(limit, elem) {
$(this).on("keyup focus", function() {
setCount(this, elem);
});
function setCount(src, elem) {
var chars = src.value.length;
if (chars > limit) {
src.value = src.value.substr(0, limit);
chars = limit;
}
elem.html( limit – chars );
}
setCount($(this)[0], elem);
}
});
})(jQuery);

//To setup the limiter, simply include a call similar to the one below:
var elem = $("#chars");
$("#text").limiter(100, elem);

/*
The first parameter is the character limit integer and the second is a jQuery
element representing the target object to display the characters remaining.
This is not a replacement for the maxlength parameter or server-side validation,
just a visual way to represent the limit.
*/

[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Shares