Home > database >  The event of second set of dynamically created buttons refuses to work
The event of second set of dynamically created buttons refuses to work

Time:06-16

I wrote up a code that displays food items on the screen by creating elements of varied tags dynamically. And I've placed the entire process in one function called displayMenuItems. Now the first set of dynamically created buttons (i.e 'add-btn' buttons), when I add an event to them, the event will fire without a hitch when clicked. However the second set of dynamically created buttons (i.e 'delete-btn' buttons), when an event is added to them, the event will not fire when clicked. I've no idea why this complication arises when the code of the second set of buttons is similar to the first set of buttons. Could you fix this problem, I would really appreciate it?

const menu = [
  {
    id: 1,
    title: "GUNPOWDER GOBHI",
    category: "Small Plates",
    price: 16.99,
    img: "sp1.png",
    desc: `Crispy Cauliflower, Spicy Lentil Dust`,
  },
  {
    id: 2,
    title: "SHRIMP KOLIWADA",
    category: "Small Plates",
    price: 13.99,
    img: "sp2.jpg",
    desc: `Crispy Popcorn Style Fritters, Pickled Mango Sauce`,
  },
  {
    id: 3,
    title: "GHEE ROAST CHICKEN WINGS",
    category: "Small Plates",
    price: 6.99,
    img: "sp3.jpg",
    desc: `Kundapur Chicken Masala`,
  },
]

const sectionCenter = document.querySelector(".section-center");
const listContainer = document.querySelector('.list-container');

window.addEventListener("DOMContentLoaded", function () {
  diplayMenuItems(menu);
});

function diplayMenuItems(menuItems) {
  let displayMenu = menuItems.map(function (item) {

    return `<article >
          <img src=${item.img} alt=${item.title}  />
          <div >
            <h4>${item.title}</h4>
            <h4 >$${item.price}</h4>
            <p >
              ${item.desc}
            </p>
            <button  data-title="${item.title}" data-price="$${item.price}">Add To List</button> 
          </div>
        </article>`;
  });
  displayMenu = displayMenu.join("");

  sectionCenter.innerHTML = displayMenu;

  const addBtns = document.querySelectorAll('.add-btn');

addBtns.forEach(function(btn){
btn.addEventListener('click', function(e){
    const title = e.currentTarget.dataset.title;
    const price = e.currentTarget.dataset.price;
    const para = document.createElement('div');
    para.classList.add('item-list');
    para.innerHTML = `<p >${title}</p>
     <p >${price}</p> 
     <button  data-title="${title}">x</button>`
listContainer.appendChild(para);
});
});

const deleteBtns = document.querySelectorAll('.delete-btn'); 

deleteBtns.forEach(function(btn){
  btn.addEventListener('click', function(e){
      const title = e.currentTarget.dataset.title;
    console.log(title);
    

  });
});
}

CodePudding user response:

delete-btns elements are not generated initially, but your events are only added for the first time, so that's why all your delete events are not applied when you add them into DOM.

I'd suggest that you should add an event directly on the newly added delete button every time.

const menu = [{
    id: 1,
    title: "GUNPOWDER GOBHI",
    category: "Small Plates",
    price: 16.99,
    img: "sp1.png",
    desc: `Crispy Cauliflower, Spicy Lentil Dust`,
  },
  {
    id: 2,
    title: "SHRIMP KOLIWADA",
    category: "Small Plates",
    price: 13.99,
    img: "sp2.jpg",
    desc: `Crispy Popcorn Style Fritters, Pickled Mango Sauce`,
  },
  {
    id: 3,
    title: "GHEE ROAST CHICKEN WINGS",
    category: "Small Plates",
    price: 6.99,
    img: "sp3.jpg",
    desc: `Kundapur Chicken Masala`,
  },
]

const sectionCenter = document.querySelector(".section-center");
const listContainer = document.querySelector('.list-container');

window.addEventListener("DOMContentLoaded", function() {
  diplayMenuItems(menu);
});

//introduce `handleDelete` here
function handleDelete(element) {
    const title = element.dataset.title;
    console.log(title);
  }

function diplayMenuItems(menuItems) {
  let displayMenu = menuItems.map(function(item) {
    return `<article >
          <img src=${item.img} alt=${item.title}  />
          <div >
            <h4>${item.title}</h4>
            <h4 >$${item.price}</h4>
            <p >
              ${item.desc}
            </p>
            <button  data-title="${item.title}" data-price="$${item.price}">Add To List</button> 
          </div>
        </article>`;
  });
  displayMenu = displayMenu.join("");

  sectionCenter.innerHTML = displayMenu;

  const addBtns = document.querySelectorAll('.add-btn');
  
  //Add `handleDelete` directly
  addBtns.forEach(function(btn) {
    btn.addEventListener('click', function(e) {
      const title = e.currentTarget.dataset.title;
      const price = e.currentTarget.dataset.price;
      const para = document.createElement('div');
      para.classList.add('item-list');
      para.innerHTML = `<p >${title}</p>
     <p >${price}</p> 
     <button  data-title="${title}" onclick="handleDelete(this)">x</button>`
      listContainer.appendChild(para);
    });
  });
}
<div >

</div>
<div >

</div>

  • Related