-1

My problem is, that even when I use .on, the click event over added div with class added does not triggers. This is my script from page.

$(".added").on("click", function () { alert("halo") });

$("#nextAdress").on("click",function (event) {
    event.preventDefault();
    $("#trainerRegistrationFields").append('<div class="added">adsa</div>');
}

Can you please help me so the click event will trigger also on the dynamically added element with class added?

Tahnk you in advance

PSL
  • 120,386
  • 19
  • 245
  • 237
marek_lani
  • 3,481
  • 4
  • 24
  • 44
  • 1
    Variations on this question are one of the most frequently asked questions about jquery on SO. I googled your question title and the top 5 responses are all stackoverflow questions with the correct answer. – Zach Lysobey Sep 17 '13 at 20:17

1 Answers1

12

You can use event delegation syntax of on for dynamically added element.

$("#trainerRegistrationFields").on("click",".added", function (){ 
    alert("halo") ;
});

In your code you are binding the handler only to the element that existed in DOM during the time of event binding. You can also do this way:

or add the handler here while you append the item.

   function handleClick(){
      alert("halo");
   }

   $(".added").on("click", handleClick); //for the already existing elements

   $("#nextAdress").on("click",function (event) {
       event.preventDefault();
       $("#trainerRegistrationFields").append($('<div class="added">adsa</div>').on('click', handleClick));
   }
PSL
  • 120,386
  • 19
  • 245
  • 237