Domanda

I have a shopping cart application that will change the cart prices on the page 'on-the-fly' using an AJAX request using the following updateCart() function - it calls the render_cart() function to display each item in the basket using an 'keyup' event.

For some reason it all works fine on the initial keyup press - but if I attempt to do this again it doesnt' work, even though I can see the .cart-qty class on the input field, can anyone suggest why this is happening?

// on keyup event call the update cart function
$(".cart-qty").on('keyup',function( e ) {    
    var qty = $(this).val(); // e.g '2' 
    var rowid = $(this).data("rowid"); // e.g 740fdjhirtj3swnjf463

    $( ".basket-item" ).remove();
    updateCart( qty, rowid );

} );

function updateCart( qty, rowid ){
$.ajax({
        type: "POST",
        url: "/cart/ajax_add_item",
        data: { rowid: rowid, qty: qty },
        dataType: 'json',
        success: function(data){                
            render_cart(data);
        }           
    });
}

function render_cart(json) {

total = json.total;
cart = json.contents;

var html = '';
if (cart) {
    $.each(cart, function (i, item) {
      html += '<div class="basket-item"><div class="col-sm-6 col-no-pad"><p><img class="img-responsive" src="'+ item.custom.image +'" alt="'+ item.name +'" /></p><div class="remove-item"><p><a class="btn btn-sm btn-yellow" href="#">Remove</a></p></div></div><div class="col-sm-6 col-no-pad"><p class="model"><span class="heading">Model:</span><br />'+ item.name +'<br />'+ item.options.attributes +'</p><p class="buyer"><span class="heading">Buyer:</span>'+ item.options.merchant +'</p><p class="price"><span class="heading">Price:</span>&#36;'+ item.subtotal.toFixed(2) +'</p><p class="condition"><span class="heading">Condition:</span>'+ item.options.condition +'</p><p class="quantity"><span class="heading">Quantity:</span><input type="text" class="form-control cart-qty" value="'+ item.qty +'" data-rowid="'+ item.rowid +'" /></p></div></div>';
    })
}   

$('#basket_start').after( html );
$('#total-value').text( total );
}
È stato utile?

Soluzione

You need to use event delegation .on() for dynamically added elements like this

$(document).on('keyup','.cart-qty',function( e ) {  

Bind it to document or the closest static parent

Altri suggerimenti

$('.cart-qty').on('keyup', (function(event) {
    //do code
}));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top