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>
<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>