I'm trying to update the cart total every time the quantity of an product in cart is increased or decreased automatically. I tried below code but it doesn't work all the time only works once after the cart page is refreshed;
function update_cart_refresh_update_qty() {
if (is_cart()) :
?>
<script type="text/javascript">
jQuery( function($){
$('.qty').on('change', function(){
setTimeout(function() {//This is set, so it gives the update cart button time to enable from disable mode
$('input[name="update_cart"]').trigger('click');
}, 2000);
});
});
</script>
<?php
endif;
}
add_action( 'wp_footer', 'update_cart_refresh_update_qty');
I would want the cart total (update cart button to be triggered) to be updated every time there is a change in product quantity.
Thanks for your help in advance.
You need to use it as a document.body delegated event (on change
and input
events) as follow:
add_action( 'wp_footer', 'update_cart_on_item_qty_change');
function update_cart_on_item_qty_change() {
if (is_cart()) :
?>
<script type="text/javascript">
jQuery( function($){
$(document.body).on('change input', '.qty', function(){
$('button[name="update_cart"]').trigger('click');
// console.log('Cart quantity changed…');
});
});
</script>
<?php
endif;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and work.
Similar: Avoid a function to only runs once on button click in WooCommerce cart