Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop array into button onclick event

I have this array and want to loop into buttons. The first cell will be in onclick event, the second will be in innerHTML.
And append these buttons to div

The array:

rows = [
  [fun1(), 'innerhtml'],
  [fun2(), 'innerhtml'],
  [fun3(), 'innerhtml'],
];

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This will get you working as you would expect.

const fun1 = () => alert("Hello function 1");
const fun2 = () => alert("Hello function 2");
const fun3 = () => alert("Hello function 3");

const rows = [
  [fun1, 'innerhtml'],
  [fun2, 'innerhtml'],
  [fun3, 'innerhtml'],
];

const myDiv = document.getElementById('myDiv');

rows.forEach(row => {
    // Create button
    const button = document.createElement('button');

    // Apply onclick event
    button.onclick = row[0];
    button.innerHTML = row[1];

    // Append to div
    myDiv.appendChild(button);
})
const fun1 = () => alert("Hello function 1");
const fun2 = () => alert("Hello function 2");
const fun3 = () => alert("Hello function 3");

const rows = [
  [fun1, 'innerhtml'],
  [fun2, 'innerhtml'],
  [fun3, 'innerhtml'],
];

const myDiv = document.getElementById('myDiv');

rows.forEach(row => {
    // Create button
    const button = document.createElement('button');

    // Apply onclick event
    button.onclick = row[0];
    button.innerHTML = row[1];

    // Append to div
    myDiv.appendChild(button);
})
<div id="myDiv"></div>

The comments should explain what is happening throughout my code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading