I have a simple setup: Two buttons with different values. I want to use the .each() function from jquery to add an click event listener to each of the buttons that simply logs the values of each button. But somehow when using .each(), jquery overwrites the click handler for the previous button(s). This leaves me with two questions:
- Why is that?
- How do add individual event listeners to a collection of jquery objects?
See code below
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(() => {
$(`button[toggle]`).each((_, button) => {
let $toggle = $(button);
type = $toggle.attr("type");
value = $toggle.attr("value");
$toggle.on("click", () => {
console.log(type, value);
});
});
});
</script>
</head>
<body>
<div>
<button toggle type="one" value="true">One</button>
<button toggle type="two" value="false">Two</button>
</div>
</body>
</html>