I have some data fetched and they all have the same buttons for opening modal, but each modal should have content about that specific item that has been clicked.
Button is shown on all items in the row, but when I click it it opens modal only on the first item in the row.
I have simple button in HTML
// this is part of fetched items in a row, each item has this button
<div>
<button id="openUniqueModal">
BUTTON
</button>
</div>
And open function in JS
let openUniqueModalBtn = document.getElementById('openUniqueModal');
if (openUniqueModalBtn != null) {
document.getElementById(
'openUniqueModal'
).onclick = function () {
modal.style.display = 'block';
};
.....
.....
How can I achieve that each button item in row will get triggered onclick? Do I have to loop through it in JS code?
EDIT:
another approach
<button class="openUniqueModal">BUTTON</button>
document
.querySelectorAll('.openUniqueModal')
.addEventListener('click', (event) => {
myModal.style.display = 'block';
});
2
Answers
You don’t need to attach event listener to every button instead you can use add a common class to add buttons and then add listener just once
you can use Zohaib Ijaz’s answer and you can even add a wild card if you want to the ‘.btn’ phrase.
Please don’t use duplicate ids on elements. as button ‘openUniqueModal’ will be duplicated in your dom for each row as there will be no increment on the id.
Having elements with the same id will cause lots of problems when it comes to industrial.
if you’re using jquery you use the below function,
*I would’ve added this as a comment in Zohaib Ijaz’s answer but I don’t have enough permission.