0

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);
    });
}
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • @j08691 Sorry for the spelling, but it's still not working. – Julia Andriessan Mar 05 '23 at 19:51
  • Change the for loop to: `for (let i = 0; ...` which will scope `i` to the body of the for loop. The problem is that you defined `i` globally. After the for loop finishes `i` points to `3` and that index is obviously `undefined`. – Đinh Carabus Mar 05 '23 at 20:00

2 Answers2

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

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">
Jake
  • 862
  • 6
  • 10