简体   繁体   中英

Dynamically created form submitting with preventDefault

I have a page that lists a bunch of items with add to cart buttons, the user clicks the button it fires AJAX which adds the item to the php cart and adds the item to the sidebar for a visual cue of what's in the cart, with a remove button. Problem is, when i click the remove button it refreshes the page even though i have prevent default attached to the function

This works

$(document).ready(function(e) {
$('.additem').click(function(e) {
    e.preventDefault();
    $(this).html('Added').attr('disabled' , true);
    $(this).closest('form.form_add').submit()

});

$('form.form_add').submit(function(e) {
e.preventDefault();
$.ajax({
  type: "POST",
  url: "buy-page-handler.php",
  data: $(this).serialize(),
  dataType: "json",    
  success: function(result) {
    var id = result.id;
    var name = result.name;
    var qty = result.qty;
    var price = result.price;
    $('#sidebar').append('<div class="cart_cont">'
                            +'<div class="desc">'+name+' '+price+'</div>'
                            +'<div class="remove">'
                                +'<form method="post" class="form_delete">'
                                    +'<button type="submit" class="removeitem">Remove</button>'
                                    +'<input type="hidden" name="id" value="'+id+'">'
                                    +'<input type="hidden" name="item-remove" value="true">'
                                +'</form>'
                            +'</div>'
                        +'</div>');
      }
 });
});

This doesn't work

$('.removeitem').click(function(e) {
    e.preventDefault();
    $(this).closest('.form_delete').submit()

});

$('.form_delete').submit(function(e) {
e.preventDefault();
$.ajax({
  type: "POST",
  url: "buy-page-handler.php",
  data: $(this).serialize(),
  success: function() {
      alert("success")
      }
 });
});

This is my first attempt at using the jquery/ajax/php combination, so i'm sure its a bit rough. Any help would be greatly appreciated.

Just change:

<button type="submit" class="removeitem">Remove</button>

to:

<button type="button" class="removeitem">Remove</button>

The issue is that your class="removeitem" elements are added dynamically after the DOM is ready, so your new elements are not bound to $('.removeitem').click() . Try binding it by delegating to the parent -

$('#sidebar').on('click', '.removeitem', function(e) {
    e.preventDefault();
    $(this).closest('.form_delete').submit()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM