Home > Software engineering >  How to dynamically create event listeners and their functions for dynamically created elements?
How to dynamically create event listeners and their functions for dynamically created elements?

Time:02-05

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?

CodePudding user response:

Here's an example of how to dynamically create event listeners and their functions for dynamically created elements in JavaScript:

const parent = document.querySelector('#parent');

function createElement() {
  const el = document.createElement('div');
  el.innerHTML = 'Click me';
  el.addEventListener('click', function() {
    console.log('Element clicked');
  });
  parent.appendChild(el);
}

createElement();

In this example, the function createElement creates a div element, sets its inner HTML to Click me, and adds a click event listener to it. The event listener logs Element clicked to the console when the element is clicked. The newly created element is then added to the parent element.

CodePudding user response:

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

  • Related