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