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

Get the respective button value in a loop

once I add a group of dynamic buttons from an array and the querySelectorAll doesn’t seem to get the list of buttons.
Here my code: Where am I going wrong?

const btns = document.getElementById("container");
const textBtn = ["btn 1", "btn 2", "btn 3", "btn 4", "btn 5", "btn 6"]
for (i = 0; i < textBtn.length; i++) {
  btns.insertAdjacentHTML('beforeend', `<button  class="allbuttons" value=${textBtn[i]}>${textBtn[i]}</button>`);
}

const btn = document.querySelectorAll(".allbuttons")
for (var i = 0; i < btn.length; i++) {
  btn[i].addEventListener('click', function(event) {
    //console.log( btn[i]);
    console.log(event.target.value);
    alert(event.target.value)
  });
}
<div id="container"></div>

>Solution :

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

does it help? is it what u need?

const btns = document.getElementById("container");
const textBtn = ["btn 1", "btn 2", "btn 3", "btn 4", "btn 5", "btn 6"]
for (i = 0; i < textBtn.length; i++) {
  btns.insertAdjacentHTML('beforeend', `<input type="button" class="allbuttons" value="${textBtn[i]}">`);
}

const btn = document.querySelectorAll(".allbuttons")
for (var i = 0; i < btn.length; i++) {
  btn[i].addEventListener('click', function(event) {
    console.log(event.target.value);
    alert(event.target.value)
  });
}
<div id="container"></div>
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