0

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!

Cleptus
  • 3,446
  • 4
  • 28
  • 34
E Lon Mask
  • 39
  • 1
  • 8

2 Answers2

2

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();
verjas
  • 1,793
  • 1
  • 15
  • 18
  • Oh my god, thank you so much for your help! It's working perfectly. The only issue is that my Firefox console gives me _TypeError: parent is null_ for `parent.addEventListener("click", buttonClick);`. Can I ignore that or should that be fixed somehow? – E Lon Mask Apr 20 '19 at 11:34
  • The answer works. But may I ask why `function buttonClick(e)` has argument `e` but it is not passed in `parent.addEventListener("click", buttonClick);`? I'm just wondering the reason behind this. – yuko Apr 20 '19 at 11:37
  • Hi. The JSfiddle is working well. Please check the line: "var parent = document.getElementById('auswahl');" -> here I assume that your HTML already contains an element with an id="auswahl" (I got it from your code). If you get *null* in console => it means that your HTML doesn't have that element OR that you are running the script *before* the page loaded the element. Can you try to create a jsfiddle yourself with your HTML+JS and test it? – verjas Apr 20 '19 at 11:44
  • Hi @YuKo - that's how add​Event​Listener works -> it automatically passes to a callback function an *Event* as parameter - check the reference here: [Event​Target​.add​Event​Listener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback) – verjas Apr 20 '19 at 11:47
  • @verjas I got the problem; I had the `dobutton()` in my `window.onload` already so the `dobutton()` from your code obviously didn't like that :D – E Lon Mask Apr 20 '19 at 11:56
0

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

enter image description here

prakash r
  • 113
  • 1
  • 11