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

Words Left - JavaScript

RSS
Modified on Mon, Apr 30, 2012, 1:27 PM by Administrator Categorized as JavaScript, jQuery, and Angular

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='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;
}
/*===============================================================================================*/



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