What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?

Look at the comments on this site, with a count down. I have done it like this before, and it is simple and effective. Stack Overflow makes good use of color too.

Perhaps you don’t have enough rep to see the comment box.

It runs a little countdown while you type. At it approaches a threshold, the color changes from yellow to red. All using JavaScript, and I assume the keyup event of the textarea.

EDIT: How about having it done with jQuery?

<script language="javascript" type="text/javascript" src="https://stackoverflow.com/questions/451491/js/jquery-1.2.6.min.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready( function () {
        setMaxLength();
        $("textarea.checkMax").bind("click mouseover keyup change", function(){checkMaxLength(this.id); } )
    });

    function setMaxLength() {
        $("textarea.checkMax").each(function(i){
            intMax = $(this).attr("maxlength");
            $(this).after("<div><span id='"+this.id+"Counter'>"+intMax+"</span> remaining</div>");
        });
    }

    function checkMaxLength(strID){
        intCount = $("#"+strID).val().length;
        intMax = $("#"+strID).attr("maxlength");
        strID = "#"+strID+"Counter";
        $(strID).text(parseInt(intMax) - parseInt(intCount));
        if (intCount < (intMax * .8)) {$(strID).css("color", "#006600"); } //Good
        if (intCount > (intMax * .8)) { $(strID).css("color", "#FF9933"); } //Warning at 80%
        if (intCount > (intMax)) { $(strID).text(0).css("color", "#990000"); } //Over
    }
</script>

And the HTML is

<textarea id="text" maxlength="250" class="checkMax"></textarea>

Leave a Comment