Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Show textarea change of value length in element

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading