Improved Character Counting Remaining on Textarea with Alert

text area with maxlenght that feeds how many characters the user has remaining

by technotarek

HTML

<textarea rows="8" cols="30" data-max="99" placeholder="I got 99 problems, but characters ain't one of them"></textarea>
<span class="char-max-alert"></span>
<br>
    <br>
<textarea rows="8" cols="30" data-max="999" placeholder="999 bottles of beer on the wall"></textarea>
<span class="char-max-alert"></span>

CSS

html { margin:11px }
.over {
    color:red;
}

JavaScript

$(document).ready(function() {
    $('*[data-max]').keyup(function() {
    	// get the max chars for the input
	    var text_max = $(this).data('max');
	    // compute current length
        var text_length = $(this).val().length;
        // compute chars remaining
        var text_remaining = text_max - text_length;
        // display
        if(text_remaining<0){
        $(this).next('.char-max-alert').html('<span class="over">' + text_remaining + ' characters remaining' + '</span>');
        } else {
        $(this).next('.char-max-alert').html(text_remaining + ' characters remaining');
        }            
    });
});