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
When clicked, retrieves the value and prints it.
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