skip to Main Content

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


  1. 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

    document.querySelector('.btn').addEventListener('click', (event) => {
       // you can check button id and take different actions if needed
       // event.target.id
    });
    
    Login or Signup to reply.
  2. you can use Zohaib Ijaz’s answer and you can even add a wild card if you want to the ‘.btn’ phrase.

    • [id^=’openUniqueModal’] will match all ids starting with openUniqueModal.
    • [id$=’openUniqueModal’] will match all ids ending with openUniqueModal.
    • [id*=’openUniqueModal’] will match all ids containing openUniqueModal.

    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,

    $( "#openUniqueModal" ).on( "click", function() {
      // your desired functionality here 
     // use $( this ) to access current element
    });
    

    *I would’ve added this as a comment in Zohaib Ijaz’s answer but I don’t have enough permission.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search