Words Left - JavaScript

Overview

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

Dependencies


Sample Code

HTML

<input type='text' id='uxInstructionsTextBox' />
<div id='WordsLeft'></div> word(s) left

JavaScript

/*===============================================================================================*/
$(document).ready(function () {
    setInterval("timerClick()", 300);
});
/*===============================================================================================*/
function timerClick() {
    showWordsLeft("#uxInstructionsTextBox", "#WordsLeft", 100);
}
/*===============================================================================================*/
function showWordsLeft(inputSelector, outputSelector, maxWords) {

    var inputField = $(inputSelector);
    var n = maxWords - getWordCount(inputField.val());
    $(outputSelector).html(n);
}
/*===============================================================================================*/
function getWordCount(s) {

    s = $.trim(s);

    if (s.length == 0)
        return 0;

    var n = 1;

    for (i = 0; i < s.length; i++)
        if (s.charAt(i) == ' ')
            n++;

    return n;
}
/*===============================================================================================*/