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
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
or
Here is a more elegant method using delegation
Note the DOMContentLoaded – that is triggered when the page has loaded all HTML
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.