Im making a program that dynamically creates html elements and when you click any of those elements it should display its value in another textbox. This is the class im using to define the element:
class msg_element{
constructor(msg){
this.message = msg;
this.element = document.createElement("P");
this.element.innerHTML = this.message;
this.element.addEventListener("click", function(){
document.getElementById("update").value = this.message;
});
document.getElementById("textview").appendChild(this.element);
}
}
and this is the loop that creates the elements:
for(var i = 0; i < bmg_msg.length; i++){
var element = new msg_element(bmg_msg[i]);
}
it creates all the elements correctly, but the clicking function doesnt work, it just displays "undefined" in the textbox. What can I do to fix this?
thisinside the event listener won't be the same asthisin the constructor function. You could use an=>function instead of a regular function, or you could explicitly storethisin a separate local variable in the constructor.