'Event Driven Programming: Registering input changes

I am very new to html, css, and javascript so please go easy on me. I am working on an activity that requests: Register the updateCount event handler to handle input changes for the textarea tag. Note: The function counts the number of characters in the textarea. The Javascript so far is as follows -

var textareaElement = document.getElementById("userName");
function updateCount(event) {
document.getElementById("stringLength").innerHTML = event.target.value.length;
}

// Write code here

I have absolutely no idea what it is asking of me for this problem. Both online resources and textbooks have not been very helpful.

The HTML cannot be changed in any way, forcing me to solve it with just changes the the javascript. The HTML is as follows -

<label for="userName">User name:</label>
<textarea id="userName" cols="40" rows="3"></textarea><br>
<p id="stringLength">0</p>

Any help would be much appreciated, I'm just trying to learn.



Solution 1:[1]

Try this. Add onkeyup event on the <textarea> tag then replace event.target to textareaElement to get the value

var textareaElement = document.getElementById("userName");
function updateCount() {
    document.getElementById("stringLength").innerHTML = textareaElement.value.length;
}
<label for="userName">User name:</label>
<textarea id="userName" onkeyup="updateCount()" cols="40" rows="3"></textarea><br>
<p id="stringLength">0</p>

Solution 2:[2]

When you have a reference to a DOM node (e.g, <textarea>), you can bind event handlers for the various events that it supports. In this case, we consult the HTMLTextAreaElement docs and learn that the following piece of JS would give the text length

 const textarea = document.getElementById('userName');
 const length = textarea.value.length; // textarea.textLength;

Then, we will consult the docs to determine that it is the input event that we want to bind to.

 textarea.addEventListener('input', updateCount);

Your updateCount gets as its input the input event that also contains a reference to the event target, which is the textarea.

Solution 3:[3]

var textareaElement = document.getElementById("userName");

    function textSize(event) {
       document.getElementById("stringLength").innerHTML = event.target.value.length;
    }
      textareaElement.addEventListener("input", function(event){
      document.getElementById("stringLength").innerHTML = event.target.value.length;

   });

Solution 4:[4]

I know the post is old but I just had to figure this one out for myself so for anyone else that has trouble in the future here is the line you need.

textareaElement.addEventListener("blur", updateCount);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CodeLover
Solution 2 Elias Toivanen
Solution 3 David Buck
Solution 4 F. Müller