Characters Left - JavaScript

Overview

As a convenience to the user, especially on longer input fields, a web page can show the number of characters remaining before the user hits the maximum number of characters allowed in a field. This article demonstrates a way to implement this feature.

See Also: Words Left - JavaScript

Dependencies


Sample Code

HTML

<input type='text' maxlength='50' id='FirstName' />
<div id='FirstNameCharsLeft'></div>

JavaScript

/*------------------------------------------------------------------------------------------------*/
$(document).ready(function(){
    setInterval("timerClick()", 300);
});
/*------------------------------------------------------------------------------------------------*/
function timerClick(){
    showCharsLeft('#FirstName', '#FirstNameCharsLeft');
}
/*------------------------------------------------------------------------------------------------*/
function showCharsLeft(inputSelector, outputSelector) {

    var inputField = $(inputSelector);
    var maxLength = inputField.attr('maxlength');

    if (maxLength != undefined) {
        var length = inputField.val().length;
        var charsLeft = maxLength - length;
        $(outputSelector).html(charsLeft + " character(s) left");
    }

}
/*------------------------------------------------------------------------------------------------*/