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;
}
>Solution :
There are two main problems:
-
You are calling
updateCountimmediately and pass its return value (undefined) toaddEventListener. 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
updateCountimmediatelythisrefers to the global object, not the element you want to bind the function to. -
querySelectorreturns 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>