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.
- IDs need to be unique – my code is using your ID as a class instead
- Make sure the elements exist at the time of assignment
- 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>
An
id
must be unique!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.
Well, please edit your question to alter the HTML; a minimal reproducible example is required to help you.
Your code works
Does this answer your question? How to execute a function when page has fully loaded?
Show 6 more comments