Search code examples
javascriptweb-applications

How to dynamically create event listeners and their functions for dynamically created elements?


I dynamically create a number of rows in a table. Each row has seven columns with the same controls in each columns. 1st column is a toggle meant to disable the textboxes or dropdowns in the other six columns. How can I dynamically create the event listeners and their respective functions to give each toggle their intended behaviour? What it looks like...


Solution

  • Here is the solution,

    const toggles = document.querySelectorAll('.toggle');
    
    toggles.forEach(toggle => {
      toggle.addEventListener('click', function(event) {
        const toggleRow = event.target.closest('tr');
        const textboxes = toggleRow.querySelectorAll('.textbox');
        const dropdowns = toggleRow.querySelectorAll('.dropdown');
    
        if (toggle.checked) {
          textboxes.forEach(textbox => textbox.setAttribute('disabled', true));
          dropdowns.forEach(dropdown => dropdown.setAttribute('disabled', true));
        } else {
          textboxes.forEach(textbox => textbox.removeAttribute('disabled'));
          dropdowns.forEach(dropdown => dropdown.removeAttribute('disabled'));
        }
      });
    });
    
    • Click here to view detailed explanation about EventListeners.

    hope you will get an idea about the code...