'Add eventlistener to multiple elements to execute multiple functions
I am trying to add an eventlistener to 2 objects but only get it to work with 1. There are 2 textinputs which both should execute 4 functions on input. The first is my working single element code. There are many topics that already cover this problem and have many answers but I cant figure it out. Below I have copied some of the answers that I tried.
//code 1
document.querySelector("#textinput1").addEventListener("input", function WriteText () {
document.getElementById("displaytext").innerHTML = document.getElementById("textinput1").value;
});
//Answer 1 /// In both answer 1 and 2 I have put my Function() insides into the eventlistener function///
let elementsArray = document.querySelectorAll("#textinput1, #textinput2");
elementsArray.forEach(function(elem) {
elem.addEventListener("input", function() {
document.getElementById("displaytext").innerHTML = document.getElementById("textinput1").value;
});
});
//Answer2 // Tried it like this and putting the document.querryselector lines of both textinput directly between the []
var Element1 = document.querySelector("#textinput1")
var Element2 = document.querySelector("#textinput2")
[Element1, Element2].forEach(function(element) {
element.addEventListener("input", function() {
document.getElementById("displaytext").innerHTML = document.getElementById("textinput1").value;
});
});
Solution 1:[1]
The this keyword points to the the current elem object.
let elementsArray = document.querySelectorAll("#textinput1, #textinput2");
elementsArray.forEach(function (elem) {
elem.addEventListener("input", function () {
document.getElementById("displaytext").innerHTML = this.value;
});
});
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 | Hamza Sehouli |
