-3

I am trying to get live character count + live preview of an textarea usign pure JS no Jquery, but getting some error. Here my code

var wpcomment = document.getElementById('text');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    document.getElementById('DrevCom').innerHTML = this.value;
}
function count()
{
  var total=document.getElementById("text").value;
  total=total.replace(/\s/g, '');
  document.getElementById("total").innerHTML="Total Characters:"+total.length;
}
<textarea id="text" onkeyup="count();"  placeholder="Add comments:"></textarea>



<p id="total">Total Characters:0</p>
<div id="DrevCom"></div>
Ajay Malik
  • 325
  • 4
  • 17

1 Answers1

1

You are setting the onkeyup property in HTML to count(), and then you are overwriting it with Javascript. You can only have one onKeyup property, so either use an event listener instead, or have the one function call the other.

var wpcomment = document.getElementById('text');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    document.getElementById('DrevCom').innerHTML = this.value;
    count()
}
function count()
{
  var total=document.getElementById("text").value;
  total=total.replace(/\s/g, '');
  console.log(total);
  document.getElementById("total").innerHTML="Total Characters:"+total.length;
}
<textarea id="text"  placeholder="Add comments:"></textarea>



<p id="total">Total Characters:0</p>
<div id="DrevCom"></div>
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116