-2

I'm trying to do a function which add 5 each time I'm adding character to textarea, and subtract 5 when I'm removing a character.

This is my HTML

<textarea rows="4" cols="50" id="my-area"></textarea>
<p>Chars: <span id="counter">0</span></p>

This is my JS

let area = document.getElementById("my-area"),
  counter = document.getElementById("counter"),
  count = 0;

area.onkeyup = area.onkeydown = area.onpaste = area.onchange = function() {
  if (area.value.length > count) {
    count++;
    parseInt(counter.innerHTML);
    counter.innerHTML = parseInt(counter.innerHTML + 5);
  } else if (area.value.length < count) {
    count--;
    counter.innerHTML -= 5;
  }
};

When I add a character first time it works correct - 5 is adding to innerHTML of counter, but when I add second character number is concatenated not added. Subtraction works good. How Can I fix the adding?

And the second situation: How to make it work if I add to p which id is "counter" a string "PLN" or "DOLLARS" (example: "0 PLN") and I want it to add five to the number and substract 5 after?

AKX
  • 152,115
  • 15
  • 115
  • 172

1 Answers1

2

Its because of the Type Coercion in javascript.

Instead parse it to int and then add 5

parseInt(counter.innerHTML) + 5
Monica Acha
  • 1,076
  • 9
  • 16