View Full Version : PLEASE HELP! character counter working incorrectly for reason

Nov 20th, 2009, 02:40 PM
Hi all. Can someone please help me make this code accurate so it counts the correct number of characters? when u click on the box, it should display 0. when u type in the box, it should count up by 1. when u click on the box, and u delete a character or characters, it subtracts that many


<form method="POST">

<table border="0" cellspacing="0" cellpadding="0">
<td width="100%">
<textarea onkeyDown="count_it(this)" rows="12" name="charcount" cols="60" wrap="virtual"></textarea>
<td width="100%"><div align="right"><p> <input type="text" name="displaycount" size="20"></p>


<script language="JavaScript">

function count_it(what){

Philip M
Nov 20th, 2009, 03:10 PM
Simple fixes are:-
<textarea onkeyup="count_it(this)"
<input type="text" name="displaycount" size="20" value = "0" >

But you need to allow for newlines \r\n which are counting as 2 in your method. The below script works in all browsers.

<script type = "text/javascript">

function countChar(ID){
nChar = ID.value.match(/[^\r\n]/g);
nCRLF = ID.value.match(/\n/g);
if (nChar != null){nChar = nChar.length}
else {nChar = 0}
if (nCRLF != null){nCRLF = nCRLF.length}
else {nCRLF = 0}
nChar = nChar + nCRLF;
document.getElementById("displaycount").innerHTML = "You have typed " + nChar + " characters";


<h4>Count Characters in a Text Area, including spaces and CR/LF</h4>
<textarea cols=32 rows=10 id='area1' onkeyup = "countChar(area1)">The rain in Spain falls mainly on the plain.</textarea>
<span id = "displaycount"></span>

The secret of success in life is honesty and fair dealing. If you can fake that, you've got it made. - Groucho Marx (1890 - 1977)