skip to Main Content

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.

2

Answers


  1. When clicked, retrieves the value and prints it.

    var buttons = document.getElementsByClassName("btn-outline-secondary");
    
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].addEventListener("click", function() {
        var value = this.value;
        console.log('clicked', value);
      });
    }
    <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>
    Login or Signup to reply.
    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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search