MattsBits
MattsBits - Brunel District

MattsBits

MattsBits RSS Feed - Subscribe Now!

09/04/2010 : Add A Text Counter To An HTML Text Area

Categories : | JavaScript | Views : 151 | Email Link Print

This article will explain how to add a text counter to a standard HTML textarea element.

This allows you to display remaining characters to your users as they type inside the text area. This technique can also be used with HTML text boxes.

When the character count reaches 0 the text turns red.

Add the following to the HEAD section of your HTML page :

<script type="text/javascript">
<!--
  function TextCounter(pTextField, pCountField, pMaxSize)
  // This function truncates the text in the textarea
  // if the number of characters exceeds pMaxSize

  //  pTextField  - reference to textarea
  //  pCountField - reference to field holding character count
  //  pMaxSize    - maximum number of characters to allow 
  {
  
    var vCount;
  
    if (pTextField.value.length > pMaxSize) {
      // Too much text has been entered so truncate
      pTextField.value = pTextField.value.substring(0, pMaxSize);
    } else {
      // Update remaining characters counter
      vCount = pMaxSize - pTextField.value.length;
      document.getElementById("counter").innerHTML=vCount;
      if (vCount==0) {
        // count is zero so set counter text to red
        document.getElementById("counter").style.color='#ff0000';
      } else {
        // count is positive to set counter text to black
        document.getElementById("counter").style.color='#000000';      
      }
    }
  }
// End -->
</script>


The textarea within your page BODY is defined as shown below :

<form name="myForm" action="">
<textarea id="myMessage" name="myMessage" cols=50 rows=5 
          onKeyDown="TextCounter(this.form.myMessage,this.form.counter,99);" 
          onKeyUp="TextCounter(this.form.myMessage,this.form.counter,99);">Default Text Goes Here</textarea>
<br /><span id="counter"></span> characters remaining
<script type="text/javascript">
<!--
  // Update character count on load because the textarea may
  // already contain some text
  document.getElementById("myMessage").onkeydown();
// End -->
</script>
</form>


The textarea is referred to as "myMessage" by both name and ID. You can change this to whatever you want but make sure you replace it in the five places it appears.

Technorati Tags : | javascript | html | text counter | textarea | input |

Author : Matt Hawkins  Last Edited By : Matt Hawkins  Permalink : Add A Text Counter To An HTML Text Area

 
 
 
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v2.0 - Copyright 2009-2010