skip to Main Content

I have 3 input fields for numbers, and I’d like to fire in the console log, every time I input a number in any of the 3 input fields. I’ve added a for loop for the addEventListener, but there’s still the error showing that this addEventListener part is not a function. I’d like to ask what am I missing for the code to be realized?

Thank you so much!

HTML:

<input type="number" id="no1">
<input type="number" id="no2">
<input type="number" id="no3">

JS:

const val = document.getElementsByTagName("input");

for (i = 0; i < val.length; i++) {
    val[i].addEventListener("input", () => {
        console.log(val[i].value);
    });
}

2

Answers


  1. Typo, missing the plural s in elementsByTagName

    Also console.log(val[i].value); is not known inside the eventListener you use.

    to fix that, you could do

    val[i].addEventListener("input", function() {
        console.log(this.value); // "this" is available because we use function 
    });
    

    or

    val[i].addEventListener("input", (e) => {
        console.log(e.target.value); // "this" is NOT available in an arrow function
    });
    

    Here is a more elegant method using delegation

    Note the DOMContentLoaded – that is triggered when the page has loaded all HTML

    window.addEventListener("DOMContentLoaded", () => {
      document.getElementById("numberContainer").addEventListener("input", (e) => {
        const tgt = e.target;
        if (!tgt.matches("[type=number]")) return; // or some other test for example class
        console.log(tgt.id,tgt.value)
      });
    });
    <div id="numberContainer">
    <input type="number" id="no1">
    <input type="number" id="no2">
    <input type="number" id="no3">
    </div>
    Login or Signup to reply.
  2. Your issue is that within your event handler, the val array is not defined. You should read up on closures to learn why this is the case.

    To solve your particular issue, you can make the following changes – your event handler should accept an event argument, which includes, among other things, a currentTarget attribute, which in this case will be the <input> element that fired the event.

    const val = document.getElementsByTagName("input");
    
    for (i = 0; i < val.length; i++) {
       val[i].addEventListener("input", (event) => {
            console.log(event.currentTarget.value);
    });
    }
    <input type="number" id="no1">
    <input type="number" id="no2">
    <input type="number" id="no3">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search