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

Characters Left - JavaScript

RSS
Modified on Mon, Apr 30, 2012, 1:28 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 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

  • jQuery
  • Input fields can be an <input> or a <textarea>, but must have a maxlength attribute.

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");
    }

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



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