How do I add an event listener to multiple buttons and get the value of each one depending on the one clicked. Eg:
You don't really need to add listeners to all the buttons. There is such thing in JS as Bubbling and capturing so you can wrap all your buttons
with a div
and catch all the events there. But make sure you check that the click was on a button
and not on the div
.
const wrapper = document.getElementById('wrapper');
wrapper.addEventListener('click', (event) => {
const isButton = event.target.nodeName === 'BUTTON';
if (!isButton) {
return;
}
console.dir(event.target.id);
})
div {
padding: 20px;
border: 1px solid black;
}
<div id='wrapper'>
<button id='but1'>
Button1
</button>
<button id='but2'>
Button2
</button>
<button id='but3'>
Button3
</button>
<button id='but4'>
Button4
</button>
</div>
Like Lucas's answer, this version will use classes instead of ID to select each button, and it will use a basic for loop.
<button class="btn">
Button1
</button>
<button class="btn">
Button2
</button>
<button class="btn">
Button3
</button>
<button class="btn">
Button4
</button>
The JS
var buttons = document.querySelectorAll(".btn").length;
for (var i = 0; i < buttons ; i++) {
document.querySelectorAll(".btn")[i].addEventListener("click", function() {
alert("Button Clicked");
});
}
If the buttons do not have a common class, you can use:
button[id^=but]
To select any button with id starting with the phrase but
, so it translates to but*
, where * is a wildcard match.
const btns = document.querySelectorAll('button[id^=but]')
btns.forEach(btn => {
btn.addEventListener('click', event => {
console.log( event.target.id );
});
});
<button id='but1'>Button1</button>
<button id='but2'>Button2</button>
<button id='but3'>Button3</button>
<button id='but4'>Button4</button>
In this case, you could use a class instead of id to grab every button.
<button class="btn">
Button1
</button>
<button class="btn">
Button2
</button>
<button class="btn">
Button3
</button>
<button class="btn">
Button4
</button>
And then in JS:
const buttons = document.querySelectorAll('.btn')
buttons.forEach(function(currentBtn){
currentBtn.addEventListener('click', handleEvent)
})
You just loop over the buttons constant which hold a NodeList with all the buttons that were found. read about document.querySelectorAll