0

I'm trying to count the characters that the user types in the textarea and display that value in a span tag.

I'm receiving this error: Uncaught TypeError: Cannot read properties of undefined (reading 'length')

const prompt = document.querySelector("#floatingTextarea2");
const wordCount = document.querySelector(".word-counter")[0];

prompt.addEventListener("input", updateCount());

function updateCount() {
  const count = this.value.length;
  console.log(count);
  wordCount.innerText = count;
}

Empty
  • 21
  • 4
  • [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423) and [addEventListener("click",...) firing immediately](https://stackoverflow.com/questions/35667267) – adiga Dec 05 '22 at 10:34

2 Answers2

1

There are two main problems:

  1. You are calling updateCount immediately and pass its return value (undefined) to addEventListener. Instead you have to pass the function itself by omitting the calling parenthesis:

     prompt.addEventListener("input", updateCount);
     //                                         ^^
    

    You are getting this error because when you call updateCount immediately this refers to the global object, not the element you want to bind the function to.

  2. querySelector returns a single element, so you need to remove the [0] from your second call:

    const wordCount = document.querySelector(".word-counter");
    //                                                      ^^
    

const prompt = document.querySelector("#floatingTextarea2");
const wordCount = document.querySelector(".word-counter");

prompt.addEventListener("input", updateCount);

function updateCount() {
  const count = this.value.length;
  console.log(count);
  wordCount.innerText = count;
}
<textarea id="floatingTextarea2"></textarea>
<p>
Characters: <span class="word-counter"></span>
</p>
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Solution that worked:

Added oninput="updateCount()" to my textarea

<textarea oninput="updateCount()"></textarea>
const prompt = document.querySelector("#floatingTextarea2");
const wordCount = document.querySelector(".word-counter");

function updateCount() {
  const count = prompt.value.length;
  console.log(count);
  wordCount.innerHTML = count + "/300";
}


Empty
  • 21
  • 4