Solved

TextArea Character Counter??

Posted on 1997-10-01
3
872 Views
Last Modified: 2013-12-03
I am not sure if it can in fact be done.

I want to have a counter, count the number of characters the user inputs into a textarea as they are entered. Thus the user would see the number of characters they entered as they fill out the form.

Thanks
delvin@telusplanet.net
0
Comment
Question by:delvin
3 Comments
 
LVL 3

Accepted Solution

by:
gwalters earned 50 total points
ID: 1270893
Here it is:

---------------------------------------------------------------
<form name=form action="">
Number of Characters: <input type=text name=counter size=10><br>
<textarea name=textarea rows=10 cols=80 onfocus='hasFocus=true' onblur='hasFocus=false'>
</textarea>
</form>

<script language=JavaScript>
var hasFocus=false;
function check() {
  document.form.textarea.blur();
  document.form.counter.value =               document.form.textarea.value.length;

  if (hasFocus)
    document.form.textarea.focus();
  setTimeout('check()',100);  
}
check();
</script>
----------------------------------------------------------------

We check the textarea every 100ms.  However, that's not enough.  If they're typing in it, it won't change until they leave the textarea.  So we force them to leave (blur), set the counter, then put them back ONLY if they were there in the first place (focus).


0
 

Author Comment

by:delvin
ID: 1270894
Awesome!  Thank you very much!
0
 

Expert Comment

by:jsWalter
ID: 8288906
Here is a real dynamic version.

It even displays a status bar for you.

Just read the directions and your in business!

jsWalter

========================

/* Place this block at the end of your HTML file

<script src='./TextArea_limit-bar.js'
        language='JavaScript'
        type='text/javascript'>
    <!-- //  
        //   Custom methods for control and display
       //    of status bar for TEXTAREA
      //
     //   Hide JavaScript Code from Browser.
    //    Do not remove these lines of code.
   //     The code will be 'INCLUDED' at run time.
  //      Create another <SCRIPT> block if you want
 //       to use additional code.
//  -->
</script>

*/

// ==========================================================================
//      TextArea_limit-bar.js
//      by Walter Torres <walter@torres.ws>
//      Copyright 2003
//      World Wide Rights Reserved
//
// Assitance From:
//    Adrian Cotter
//    Abraham Okomanyi
//
//      This script can be used for personal use only.
//      It CAN NOT be distributed without the express
//      written permission of the Auther.
//
//      Please send comments, corrections and suggestions to
//            Walter Torres <walter@torres.ws>
// ==========================================================================

// ==========================================================================      
// This file contains new Methods for Display Control of a status bar for
// The HTML FORM TEXTAREA Object:
//    Add a status bar display and control to any TEXTAREA desired
//    To use, just add this attribute to any TEXTAREA Objects you
//    wish to have the status limit bar associated with...
//       new atrtribute  -  progress='true'
//
// Place this code at the end of your page, or within an onLoad
// event call
//
// Remember, this code can only be called *after* your TEXTAREA Objects
// have been create by the Browser.


      // Retrieve a sub-array of all the TEXTAREA Objects
      // in this FORM.
      var aryTextAreaTags = document.getElementsByTagName("textarea");

      // Loop down all the TEXTAREA Objects in this FORM and
      // add a new method.
      for (var i = 0; i < aryTextAreaTags.length ; i++)
      {

            // We only want to do this if the Object is set for it
            if ( aryTextAreaTags[i].progress == 'true' )
            {
                  // We will need to insert our status bar after the TEXTAREA...
                  // The next few lines do just that.

                  // Create a new OBJECT
                  objBar = document.createElement("SPAN");
                  objBar.setAttribute("id",aryTextAreaTags[i].id + '_pad');
                  
                  // get the TEXTAREA and its parent
                  objTA = document.getElementsByTagName("TEXTAREA")[i];
                  objParent = objTA.parentNode;
                  
                  // insert it in the children of objectparent before the sibling of the TextArea
                  objParent.insertBefore(objBar,objTA.nextSibling);

                  // Create Bar Graph for TEXTAREA
                  objBar.innerHTML = buildStatusBar ( aryTextAreaTags[i].id  );
                  
                  // Test HTML generation
//                  document.getElementsByTagName("TEXTAREA")[i].value = objBar.innerHTML;
      
                  // Insert new Method to TEXTAREA
                  aryTextAreaTags[i].setBar = setBar;

                  // Now attach Event Actions to TEXTAREA
                  aryTextAreaTags[i].onchange   = setBar;
                  aryTextAreaTags[i].onfocus    = setBar;
                  aryTextAreaTags[i].onselect   = setBar;
                  aryTextAreaTags[i].onclick    = setBar;
                  aryTextAreaTags[i].onpaste    = setBar;
                  aryTextAreaTags[i].onkeypress = setBar;
                  aryTextAreaTags[i].onkeydown  = setBar;
                  aryTextAreaTags[i].onkeyup    = setBar;

                  // Make the default value available
                  aryTextAreaTags[i].setBar();
            }

      }

// Style definitions that you can modifiy
var styFontDisplay = 'block';     // Show status numbers or not [block|none]
var styFontFamily  = 'tahoma';    // Font to display the status numbers
var styFontSize    = '6pt';       // Size of status numbers
var styFontColor   = 'black';     // Color of status numbers
var styFillColor   = '#0000ff';   // Color of status bar
var styEmptyColor  = '#cccccc';   // Color of status bar


// Create Style Sheets
taStatusStyle ();


// Define what the status bar will look like
function buildStatusBar ( strTAname )
{

      var strTemp = '';

    strTemp += '<table cellpadding="0" cellspacing="0" border="0" width="350">';
    strTemp += '<tr>';
    strTemp += '<td width="0" align="center" class="filler" name="filler" id="filler">';
    strTemp += '   <img src="/images/trans-spacer.gif" name="' + strTAname + '_fill" id="' + strTAname + '_fill" height="5" width="0">';
      strTemp += '</td>';
    strTemp += '<td width="0" align="center" class="blank" name="blank" id="blank">';
    strTemp += '   <img src="/images/trans-spacer.gif" name="' + strTAname + '_blank" id="' + strTAname + '_blank" height="5" width="0">';
      strTemp += '</td></tr><tr>';
    strTemp += '<td width="0" align="center" class="fillerValue" name="' + strTAname + '_fillNum" id="' + strTAname + '_fillNum">0</td>';
    strTemp += '<td width="350" align="center" class="fillerValue" name="' + strTAname + '_blankNum" id="' + strTAname + '_blankNum">500</td>';
    strTemp += '</tr> </table>';

      return strTemp
}

//**************************************
// Original Header from www.Planet-Source-Code.com
//     Name: Dynamic Character Counter and Status Bar
//     Description:I found this code in use on zeal.com and it was unique so
//                 I thought I'd post it here. This Javascript allows the user
//                 to type characters in a box and shows the percent complete
//                 of their allowable max number of characters as a dynamically
//                 changing status bar!
//     By: Ian Ippolito (RAC)
//
//   Inputs:None
//   Returns:None
//   Assumes:None
//   Side Effects:None
//
//   This code is copyrighted and has limited warranties.
//   Please see http://www.Planet-Source-Code.com/xq/ASP/txtCodeId.1899/lngWId.2/qx/vb/scripts/ShowCode.htm
//   for details.
//
//**************************************
// New Header
//
//      setBar.js
//      by Walter Torres <walter@torres.ws>
//
// I picked the orignal version up from Planet-Source-Code.com
// I could not locate the referenced version at ZEAL.com
// Since this is from someone (I can't find who), I don't think
// Planet-Source-Code.com has any copyright claims to it.
//
// I made quite a few modification to it to run as an event driven method.
//
// Please let me know if:
//    - you know who created the orginal
//    - have ideas on how to improve this
//
//**************************************

   function setBar ( objTextArea )
{
      // Get name of given TEXTAREA
      var strName = this.id;

      // What is the limit set at for this TEXTAREA
      var intLimit = new Number ( this.max );

      // Create Object Reference to Bar of this TEXTAREA
      var objThisBar = this.pad

      // Create reference to FILL bar
      var objFillBar = eval ( 'document.all.' + strName + '_fill' );
      var objFillNum = eval ( 'document.all.' + strName + '_fillNum' );

      // Create reference to Empty bar
      var objBlankBar = eval ( 'document.all.' + strName + '_blank' );
      var objBlankNum = eval ( 'document.all.' + strName + '_blankNum' );


    var intCharCount = new Number ( intLimit - this.value.length );

    if ( intCharCount < 0 )
      {
            this.value = this.value.substring( 0, intLimit );
            intCharCount = 0;
      }

      // Set size of bar chart
    objFillBar.width = 350 * ( intLimit - intCharCount ) / intLimit;
    objBlankBar.width = 350 * ( intCharCount / intLimit );

      // Set ALT TEXT for each side of bar chart
    objFillBar.alt   = intLimit - intCharEntered + " chars entered";
    objBlankBar.alt  = intCharCount + " chars available";

      // Only show if greater than ZERO
      objFillNum.innerHTML = ( this.value.length > 0 ) ? this.value.length : '' ;

      // Only show if greater than ZERO
      objBlankNum.innerHTML = ( ( intLimit - this.value.length ) > 0 ) ? ( intLimit - this.value.length ) : '';

}


// Create Style sheets for status bar display attributes
// Do not modifiy here.
// Locate style variables above and modify from there
function taStatusStyle ()
{
      var strStyleBlock = '';
      
      strStyleBlock += '<style>';
      strStyleBlock += 'TD.fillerValue{font-family: ' + styFontFamily + ';font-size: ' + styFontSize + ';text-align: center; color: ' + styFontColor + '; display: ' + styFontDisplay + ';}';
      strStyleBlock += 'TD.filler{background-color: #0000ff;}';
      strStyleBlock += 'TD.blank{background-color: #cccccc;}';
      strStyleBlock += '</style>';

      document.write ( strStyleBlock );
}

// eof
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now