Input & Textarea Character Limit Counter with jQuery

Javascript, jQuery 44 responses so far

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.

(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.

Click here for the demo.

The following two tabs change content below.
Scriptiny is a web development blog featuring fresh articles on JavaScript, AJAX, CSS, XHTML, PHP, Photoshop and more.

Latest posts by Michael (see all)

  • maxw3st

    Just happen to be working on a little project involving capture of selected text strings in a textarea, and this should fit right in. Thanks for sharing.

  • Peter

    Cool! Although there seems to be an disconnect when you use returns. If you use a return it counts a character. For example if you use 1 return when you reach 1 character remaining you can no longer type a character until you remove the return.

    I so it seems as though the # that limits your characters is counting a return as 2 but the char remaining is only counting it as 1.

  • Bruno

    Really really nice, thanks for sharing!

  • http://twitter.com/MikhailAnikin Mikhail Anikin

    Here was a comment on some errors while counting characters in posts containning returns (new lines). It is gone but it was true.

  • scherbak

    keyup is good idea but keydown must be here. If i press and hold key for example "a" setCout() does not fire. Fix it please

  • nauman

    this is very infomrative
    http://harbingersol.com/

  • Junko

    Not work Ctrl+Z in IE9.

  • Rahul online

    Rahul Online Services
    Pvt. Ltd.

    Rahul Online Services is the best option for all your web
    based business needs. We are equipped with a strong professional team for
    website developing and designing. For any styles of excellence in web contact
    us.

    PH- +919903827804

  • Veena wad

    these worked in rare projects but there also ctr+z does not work it created lot of problem to return to the words or character previously which was………

  • Berk Goff

    This little jQuery small will let you quickly add a limit opposite to views places to show available remaining numbers. A amazing operate to involve for improved knowledge.It will also useful<a href="http://bertcompton.wordpress.com/"&gt;
    CodeIgniter developer</a>.

  • g

    dsssddd

  • Babublogging

    Its a really helpful information about "

    Input & Textarea Character Limit Counter with jQuery" and your your snippet is very helpful of very easy understanding.

  • zhou forrest

    For example if you use 1 return when you reach 1 character remaining you can no longer type a character until you remove the return

  • Spinx Inc

    Nice script used with visuals…It’s definitely not a replacement for server side validation or maximum length parameter as per the author. Thanks for sharing.

  • forrestzhou

    that's great

    By the way ,We are Millettech company. And a professional IT company in Shanghai and we've been in this field for more than 6 years and offer services including web design and development 、web hosting、website maintenance、domain name registration、search engine registration、search engine optimization、e-commerce、creative design、logo design & corporate identity、VR and 3D Animation、3D panoramic virtual tour、graphic design、software offshore outsourcing

    +86-021-68880576 millettech@gmail.com

  • watson

    The code like described works very well.

    http://www.isolcertificationtraining.com/

  • Mohsen Ansari

    After reading your information i be your die-hard fan.
    thanks for shearing it..

    https://twitter.com/GerardSaliot

  • moinhussain

    Thanks for the Information Regards <a href="http://studentsarea.com/">Education Portal </a>

  • sorlipro

    Cool

  • http://twitter.com/fabiofcardoso Fábio Cardoso

    I put this: $(this).attr('maxlength', limit);, after the line: setCount($(this)[0], elem);

  • https://twitter.com/jessicadooley Jessica Dooley

    Thanks so much for this little gem!

    I’ve tried other character counters but this was the lightest and easiest to implement of all those I’ve tried!

    Love it :)

  • http://www.abhijeetsurana.com Abhijeet

    THanks for code..

  • http://www.abhijeetsurana.com Abhijeet

    this is good article.

    For dynamic & Responsive website, please contact

  • Mike

    This doesn’t work if there are several consecutive enter characters. It limits too early.

  • Dusan

    Very handy! Thanks. It works perfectly.

  • Swati Patel

    I have tried and used many character limit & counters but this one is really very light, handy and works on copy & paste too… Great Job! :)

  • Kevin

    I'm trying to use it with multiple fields but it's only working with the first one. Is there anything else I need to know? Thanks.

    Anyways, good work!

  • hatchetfaceugly

    Got any suggestions on how to set the minimum limit of characters in addition to the maximum allowed in this code? For example, I'd like to require a minimum of 120 characters and a maximum of 320. Thanks for any suggestions.

  • Rob

    nice visual character counter plugin here: http://wchar.websanova.com

  • Kairo

    Hey!
    Which License does this script have?

  • chandra

    hai………..

  • chandra

    i am fine

  • chandra

    i am fine tooooooooooo

  • Doc

    Very nice. Thank you for that one. Only I can't limit more than one textarea like mentioned before.

  • Doc

    Ok, I've just copied the code and renamed the functions like this:

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

    var elem2 = $("#counter_id");
    $("#textarea_id").limiter2(300, elem2);

  • doc

    sorry. this is BS. of course this .limiter function works with multiple counters….. I think this was just a cash problem…. sorry….

  • Matt

    This is a very nice solution that doesn't rely too heavily on jQuery. I do, however, suggest using the keydown event to keep a running count of the number of characters if a key is being held down (like the delete key).

    I've modified the logic a bit with a small hack to ensure all values are updated properly before running the limit and counter logic, as well as allowing the counter argument to be optional. I'm using different naming conventions as well:

    <code>
    $.fn.extend({
    limit_characters: function(max, counter){
    $(this).bind("keydown focus", function(){
    var self = this;
    window.setTimeout(function(){
    var chars = self.value.length;
    if(chars > max) {
    self.value = self.value.substr(0, max);
    chars = max;
    }
    if(typeof(counter) != 'undefined') counter.html(max-chars);
    }, 5);
    });
    }
    });
    </code>

  • Jörg

    Danke, gute Arbeit, weiter so!

  • nuza

    thanks bro

  • Paul Smith

    superb! good implementation and a very clear explanation.

  • Ronel Gonzales

    thanks

  • Marco

    Very nice. I suggest to add "paste" after keyup & focus, or user can exceed
    the limit with copy-paste ;)

    $(this).on("keyup focus paste", function() {
    setCount(this, elem);
    });

  • Yura

    … and i just added a small tick icon when not characters left. ;)

    $.fn.extend({
    limit_characters: function(max, counter){
    $(this).bind("keydown focus", function(){
    var self = this;
    window.setTimeout(function(){
    var chars = self.value.length;
    if(chars > max) {
    self.value = self.value.substr(0, max);
    chars = max;
    }
    if ((max-chars == 0) && (typeof(counter) != 'undefined')) {
    elem.html('<img src="images/tick-icon.png" />');
    }
    else {
    counter.html(max-chars);
    }
    }, 5);
    });
    }
    });

  • Alexander Gabriel

    node-noob question: How can I put this in a node.js module and require it?

x
Loading...