The html buttons are created in JavaScript, each with their own ID. They activate the same function when pressed, and I want to know which button is pressed. I use this.id
to see the ID of the button pressed. I think, since I haven't retrieved the buttons in JavaScript (eg. button = document.getElementById('button')
), it doesn't work. I don't know how to do this with HTML elements created inside the script.
var paragraph = document.getElementById('paragraph');
var cabins = [1,2,3];
for (var i = 0; i < cabins.length; i++) {
paragraph.innerHTML += "Cabin " + cabins[i] + "<br><br><button id='cabin" + cabins[i] +"' onclick='purchaseCabin()'>Purchase</button><br><br>"
}
function purchaseCabin() {
var cabinId = this.id;
console.log(cabinId);
}
<p id="paragraph"></p>
Expected result: the ID of the pressed button is written in the console
Actual result: "undefined" is written in the console
this
inside the function refers to Window
which does not have the property id
, thus you get undefined
:
Pass this
object to the function so that you can refer that inside the function:
var paragraph = document.getElementById('paragraph');
var cabins = [1,2,3];
for (var i = 0; i < cabins.length; i++) {
paragraph.innerHTML += "Cabin " + cabins[i] + "<br><br><button id='cabin" + cabins[i] +"' onclick='purchaseCabin(this)'>Purchase</button><br><br>"
}
function purchaseCabin(current) {
//console.log(this.constructor.name); // Window
var cabinId = current.id;
console.log(cabinId);
}
<p id="paragraph"></p>