MattsBits
MattsBits

MattsBits

Add A Text Counter To An HTML Text Area  

by Matt Hawkins, 09/04/2010
Categories : JavaScript : HTML & CSS

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,pMaxSize)
// This function truncates the text in the textarea
// if the number of characters exceeds pMaxSize

// pTextField - string ID of text box
// pMaxSize - maximum number of characters to allow
{

var vCount;
var textbox = document.getElementById(pTextField);
var counter = document.getElementById(pTextField + '_counter');

if (textbox.value.length > pMaxSize) {
// Too much text has been entered so truncate
textbox.value = textbox.value.substring(0, pMaxSize);
} else {
// Update remaining characters counter
vCount = pMaxSize - textbox.value.length;
counter.innerHTML=textbox.value.length + ' of ' + pMaxSize;

if (textbox.value.length>(pMaxSize*0.8)) {
// Twenty percent of chars remaining so set counter text to red
counter.style.color='#ff0000';
} else {
// count is positive to set counter text to black
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</txtarea>
<br /><span id="myMessage_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.

Author : Matt Hawkins  Last Edit By : Matt Hawkins
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v3.0 - Copyright 2009-2022