Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Page History: Words Left - JavaScript

Compare Page Revisions



« Older Revision - Back to Page History - Current Revision


Page Revision: Mon, Apr 30, 2012, 1:27 PM


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

  • jQuery

Sample Code

HTML

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

JavaScript

/*===============================================================================================*/
$(document).ready(function () {
    setInterval("timerClick()", 300);
});
/*===============================================================================================*/
function timerClick() {
    showWordsLeft("#uxFirstNameTextBox", "#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;
}
/*===============================================================================================*/



ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.