How do I get the value from identical buttons using class and Javascript

I have two buttons, when I click on one of these buttons I want to get the value associated to the button. I want to use Javascript and not JQuery.

This is the code I have tried but I don’t get any response

var elements = document.getElementsByClassName("btn btn-outline-secondary");

var myFunction = function() {
    console.log("lbd button clicked");
    let arrayID = this.getAttribute("value");
    console.log(arrayID);
};

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', myFunction, false);
};
<button id="lbd-btn" value="1" class="btn btn-outline-secondary" style="border-radius: 20px; font-size: 14px;">Discover</button>
<button id="lbd-btn" value="2" class="btn btn-outline-secondary" style="border-radius: 20px; font-size: 14px;">Discover</button>

I thought about changing the class name to remove the whitespace but no luck.

Any help would be great.

  • 7

    An id must be unique!

    – 

  • 3

    I’ve moved your code into a runnable snippet, seems to be working just fine. Even tho this is invalid HTML due to the duplicate ID.

    – 

  • 2

    Well, please edit your question to alter the HTML; a minimal reproducible example is required to help you.

    – 

  • 1

    Your code works

    – 

  • 1

    Does this answer your question? How to execute a function when page has fully loaded?

    – 

  1. IDs need to be unique – my code is using your ID as a class instead
  2. Make sure the elements exist at the time of assignment
  3. Delegate the click from the nearest container

This code does not need the ID and will handle dynamically added buttons as long as they are added to whatever you decide is the nearest common container

window.addEventListener("DOMContentLoaded", () => { // when the page has loaded
  const container = document.getElementById("buttonContainer"); // nearest common container
  container.addEventListener('click', event => {
    const tgt = event.target.closest(".lbd-btn"); // handle child elements of the button
    if (!tgt) return; // we are not interested
    console.log("lbd button clicked"); // this can be a dynamically inserted button
    let arrayID = tgt.value; // simpler than getAttribute
    console.log(arrayID);
  });
});
.lbd-btn {
  border-radius: 20px;
  font-size: 14px;
}
<div id="buttonContainer">
  <button value="1" class="lbd-btn btn btn-outline-secondary">Discover</button>
  <button value="2" class="lbd-btn btn btn-outline-secondary">Discover</button>
</div>

Leave a Comment