0

[Solved][JavaScript] Adding onkeyup event to an array of elements with the same CSS class in a loop

I would like to add an onkeyup event to all input fields with the class ".calculate" which will run the calculateThis() function on every key up. The tutorials I've read on here and online have all used single elements, such as ones that they get with document.getElementById. But I need it for a group of elements, so I tried doing it with a for loop. Attempt #1: var calc = document.getElementsByClassName("calculate"); for (var n = 0; n < calc.length; n++) { calc[n].addEventListener("keyup", calculateThis); } Attempt #2: var calc = document.getElementsByClassName("calculate"); for (var n = 0; n < calc.length; n++) { calc[n].onkeyup = function() { calculateThis(); } } I know this can be done by calling the function directly on each input: <input type="text" class="calculate" onkeyup="calculateThis()"> but I'd like to add it through JavaScript if possible. Any help would be appreciated. Thanks in advance! Edit: Nevermind, I figured it out :)

25th Mar 2020, 7:39 AM
Alyssa
Alyssa - avatar
5 Respuestas
+ 3
If it still does not work. Maybe the problem is that the JS get loaded befor the HTML. In this case try this: window.onload = function () { var calc = document.getElementsByClassName("calculate"); for(let input of calc) { input.addEventListener("keyup", calculateThis); } function calculateThis() { console.log("success"); } }
25th Mar 2020, 8:44 AM
yochanan sheinberger
yochanan sheinberger - avatar
+ 4
Event delegation Modularity Demo for you : https://code.sololearn.com/Wc3b4508uFJe/?ref=app
25th Mar 2020, 8:59 AM
Gordon
Gordon - avatar
+ 1
Attempt #1 should work. But you can try the for of loop to. for(let input of calc) { input.addEventListener("keyup", calculateThis); }
25th Mar 2020, 8:16 AM
yochanan sheinberger
yochanan sheinberger - avatar
0
how we calculate two or more total
6th Oct 2021, 9:27 AM
LOKESH
LOKESH - avatar
0
test
26th Oct 2022, 5:44 AM
Kingshuk Biswas
Kingshuk Biswas - avatar