0

Please help. Click event not working inside getJson loop. There is no error on console tab.

  $.getJSON('/assets/data/maindata.json', function(bpds) {
    
        bpds.forEach((data) => {
              
          mainProductCard += '<div class="Qlty"><button value="'+ data.customFields[0].value +'">Ordinary</button><button value="'+ data.customFields[1].value +'">Premium</button></div>'
          
        }); //end of for each
    
        $('#mainDiv').append(mainProductCard)

    }); //end of getjson
        
    
$(".Qlty button").click(function() {

  alert("alert working");

});
jmozzart
  • 123
  • 8
  • your issue is that the click event is not being attached to the buttons inside the $(".Qlty") elements because the event binding code executes before the buttons are added to the DOM. use event delegation to attach the click event to a parent element that already exists in the DOM. In this case, you can attach the event to the $('#mainDiv') element and use a selector to target the buttons within it. let me share my code in answer. – Louis May 19 '23 at 03:13
  • Does this answer your question? [Direct vs. Delegated - jQuery .on()](https://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on) – Alon Eitan May 19 '23 at 03:39

1 Answers1

2
$.getJSON('/assets/data/maindata.json', function(bpds) {
  bpds.forEach((data) => {
    mainProductCard += '<div class="Qlty"><button value="'+ data.customFields[0].value +'">Ordinary</button><button value="'+ data.customFields[1].value +'">Premium</button></div>';
  });

  $('#mainDiv').append(mainProductCard);
  
  // Attach the click event using event delegation
  $('#mainDiv').on('click', '.Qlty button', function() {
    alert("alert working");
  });
});

Does this help you?

Louis
  • 532
  • 1
  • 2
  • 11