0

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

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.