Reputation: 49
So I am creating a few buttons dynamically via javascript.
function dobutton() {
for (i=0; i<eigenschaften; i++){
var btn = document.createElement("BUTTON");
btn.className = 'button black';
btn.id = eigenschaftsarray[i];
btn.name = 'pickbutton';
btn.innerHTML = eigenschaftsarray[i].split("_").join(" ");
document.getElementById('auswahl').appendChild(btn);
document.getElementById('auswahl').innerHTML += " ";
}
}
eigenschaften = 39
eigenschaftsarray = just some names
Now I want to get the ID of the button I click. I was not able to get anything from this JavaScript - onClick to get the ID of the clicked button running because of my method using js to create those buttons. Adding the onClick event to my code just instantly alerts 39 "unknown".
Can someone provide me some help, I am just using Javascript, no jQuery :)
Thanks!
Upvotes: 0
Views: 2833
Reputation: 113
Step 1: Add Buttons Dynamically To DOM
HTML :
<body>
<h1>
HelloWorld HelloWorld
</h1>
<div id="stackMe"></div>
</body>
Javascript :
const data = [{'Name' : 'Hello', 'Id' : 1},
{'Name' : 'World', 'Id' : 2}];
window.addEventListener('DOMContentLoaded', function (){
console.log('DOM loaded');
generateButtons(data);
});
function generateButtons(data) {
const buttonResults = data.map(bt =>`<button id= "${bt.Id}" onClick="btClicked(${bt.Id})">Button ${ bt.Name }</button>`);
document.getElementById("stackMe").innerHTML = buttonResults;
}
Step 2: Add an event listener for the button clicked
function btClicked(currentId) {
let elementClicked = data.find(d => d.Id == currentId);
console.log(elementClicked);
}
Output: Out after the button is clicked
Upvotes: 0
Reputation: 1793
When you create elements dynamically, you have to keep in mind that you can bind events to them only after they are available in the DOM.
Here is a working demo: jsfiddle demo
In the demo, we bind an event listener ("click") to the parent that contains the buttons. The parent is a static element, already available in the DOM.
The JavaScript code is:
var eigenschaften = 3;
var eigenschaftsarray = ["b0","b1","b2"];
// fn: detect if a button was clicked -> get id
function buttonClick(e){
// check if the clicked element is a button
if (e.target.tagName.toLowerCase() == "button") {
var btn = e.target;
// alert the user what button was clicked
alert("button id="+btn.id);
}
}
// fn: create buttons dynamically
function dobutton() {
// identify parent
var parent = document.getElementById('auswahl');
// create buttons dynamically
for (i=0; i<eigenschaften; i++){
var btn = document.createElement("button");
btn.className = 'button black';
btn.id = eigenschaftsarray[i];
btn.name = 'pickbutton';
btn.innerHTML = eigenschaftsarray[i].split("_").join(" ");
// append btn to parent
parent.appendChild(btn);
parent.innerHTML += " ";
}
// add "click" listener on parent
parent.addEventListener("click", buttonClick);
}
// create buttons
dobutton();
Upvotes: 2