1

I have an mvc application that shows the purchasing history of a client. When a client clicks on a specific order from his purchase history, I show the user a list of the products that where on the selected order. Till here everything works well. Now when the use clicks on a product from the selected order, I get the current product details using $.ajax returning an html result from a partial view and show it in a jquery.dialog. It works find except that I have a button in the popup with class="addToCart", in the main page I have

$(".addToCart").on(click, function(e){
    ....
}); 

but this command is never called except if i add this script in the partial view.

Any idea?

  • Add quotes around `click` in your command: `($(".addToCart").on("click", function(e){});` – krillgar Sep 01 '17 at 16:38
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) –  Sep 02 '17 at 08:08

1 Answers1

0

The click binding you're using is called a "direct" binding, which will only attach the handler to elements that already exist. This is why it worked when you added the code in the partial view.

The following code will work for all the elements with 'addToCart' class in the body, whether already present, or dynamically added later.

$('body').on('click', '.addToCart', function() {
    ....
});
adiga
  • 34,372
  • 9
  • 61
  • 83