John C.
John C.

Reputation: 43

Javascript Character Counter Duplication

I'm trying to duplicated the following code but no matter what combination I attempt I cannot get the second copy of it working. Basically I have two html textarea boxes that I need to character count on the same page. They can actually have the same exact count if it makes it easier, I'm not just sure how to duplicate the JS and still have it function.

function countChars(countfrom,displayto) {
  var len = document.getElementById(countfrom).value.length;
  document.getElementById(displayto).innerHTML = len;
}
<textarea id="data"
 onkeyup="countChars('data','charcount');" 
onkeydown="countChars('data','charcount');" 
onmouseout="countChars('data','charcount');"></textarea>
<span id="charcount">0</span> characters entered.

Upvotes: 1

Views: 43

Answers (1)

Sylwek
Sylwek

Reputation: 866

You have to make new textarea with other id and span to display characters count, also with other id. Then you use same function to count charaters, but with other ids

function countChars(countfrom,displayto) {
  var len = document.getElementById(countfrom).value.length;
  document.getElementById(displayto).innerHTML = len;
}
<textarea id="data" onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea>

<span id="charcount">0</span> characters entered.

<textarea id="data2" onkeyup="countChars('data2','charcount2');" onkeydown="countChars('data2','charcount2');" onmouseout="countChars('data2','charcount2');"></textarea>

<span id="charcount2">0</span> characters entered.

Upvotes: 1

Related Questions