简体   繁体   中英

Auto update cart on quantity change in Woocommerce cart page

I have a $5 fee that gets added to the order total when using lets say "Cash on Delivery". This fee should be removed when switching to "bank transfer". This fee gets removed just fine when I trigger the order review table to update by lets say changing the billing zip code. But I need it to also trigger when selecting a different payment gateway.

Here is my current code:

<script>
    $('#payment_method_bacs').on('click', function() {
    $( 'body' ).trigger( 'update_checkout' );})
</script>

Any ideas?

You can follow this to update cart via AJAX. Here is the link

jQuery(function( $ ) {
    $( "form.checkout" ).on( "click", "input.qty", function( e ) {//modify this to payment gateway radio button selection
      var data = {
      action: 'update_order_review',
      security: wc_checkout_params.update_order_review_nonce,
      post_data: $( 'form.checkout' ).serialize()
    };

    jQuery.post( add_quantity.ajax_url, data, function( response )
    {
      $( 'body' ).trigger( 'update_checkout' );
    });
  });
});

Here in above code instead of quantity update, Just add your change event of payement Gateway radio button selection

Since this part (payment methods) of the checkout being updated in the background, you should bind the click to "body" such as:

jQuery(document).ready(function(){
    jQuery('body').on('click', 'ul.payment_methods li', function(){
            console.log('payment method clicked');
    });
});

(Untested!)

Just to make this question somewhat useful for anyone who reads here in the future.. here is the script that ended up working for me. I found the answer here from this helpful guide .

    jQuery('div.woocommerce').on('click', 'input.qty', function(){ 

        jQuery("[name='update_cart']").trigger("click");

    }); 

To avoid customer click so many time make ajax call so many time:

 jQuery( function( $ ) {
    let timeout;
    $('body').on('change', 'input.qty', function(){
        if ( timeout !== undefined ) {
            clearTimeout( timeout );
        }
        timeout = setTimeout(function() {
            $("[name='update_cart']").trigger("click");
        }, 800 );
    });
} );

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