Filed Under (Javascript Code Samples) by Anoop on May-31-2007
Code (javascript)

<HTML>
 <HEAD>
  <TITLE> Javascript Character Count by WebSewak.com </TITLE>
<script language="Javascript">
function counterUpdate(opt_countedTextBox, opt_countBody, opt_maxSize) {
        var countedTextBox = opt_countedTextBox ? opt_countedTextBox : "counttxt";
        var countBody = opt_countBody ? opt_countBody : "countBody";
        var maxSize = opt_maxSize ? opt_maxSize : 1024;

        var field = document.getElementById(countedTextBox);

        if (field && field.value.length >= maxSize) {
                field.value = field.value.substring(0, maxSize);
        }
        var txtField = document.getElementById(countBody);
                if (txtField) { 
                txtField.innerHTML = field.value.length;
        }
}
</script>
 </HEAD>

 <BODY>
  <textarea id="counttxt" name="counttxt" rows="10" onkeyup="counterUpdate('counttxt', 'countBody','30');"></textarea>
 
  You typed <B><span id="countBody">0</span></b> characters
  Max. Length : 30 Chars
 </BODY>
</HTML>
 


chris on October 22nd, 2007 at 10:42 pm #

trouble with this is tht it counts up, and not down?

chris on October 22nd, 2007 at 11:54 pm #

to reverse the count order change:

txtField.innerHTML = field.value.length;

to:
txtField.innerHTML = maxSize- field.value.length;

Rajiv Kumar on February 12th, 2008 at 8:17 pm #

thanks, awesome job

rajesh on May 6th, 2008 at 3:05 pm #

a problem,
if we reset the form it wont go back to the default count.until we select the text area again …

nitz on July 30th, 2008 at 3:51 pm #

for the reset thing to work put the textarea inside a form..it’ll work

Viper on August 9th, 2008 at 10:30 pm #

Wondering how I would send the count in a e-mail?
To do this I would think you would need a readonly field

Viper on August 9th, 2008 at 10:33 pm #

I see that the count is also affected by the “enter key” any way of making it so it don’t count this as a Character?

dwalsh on November 18th, 2008 at 10:39 pm #

If I wanted to use a replace your textbox with a textbox from my form using my form how would I do that?

Greentea on December 6th, 2008 at 12:37 am #

Great stuff! Thanks:)

Post a comment
Name: 
Email: 
URL: 
Comments: