Search code examples
phpjquerywordpresswoocommercecart

Auto Update WooCommerce Cart on cart item quantity change


I want to enable an AJAX auto update when user changes the quantity (first hiding "Update cart" button) in WooCommerce cart page.

I followed the steps from this tutorial.

So basically I use this code:

jQuery(document).ready(function($) {
    let timeout;
    $('.woocommerce').on( 'change', 'input.qty', function(){
        if ( timeout !== undefined ) {
            clearTimeout( timeout );
        }
        timeout = setTimeout(function() {
            $("[name='update_cart']").trigger("click"); // trigger cart update
        }, 1000 ); // 1 second delay, half a second (500) seems comfortable too
    });
});

I've added the above script like so:

function custom_enqueue_cart_scripts() {
    error_log('custom_enqueue_cart_scripts');
    if (is_cart()) {
        error_log('is_cart()');
        wp_enqueue_script('custom-cart', get_stylesheet_directory_uri() . '/js/custom-cart.js', array('jquery'), null, true);           

    }
}
add_action('wp_enqueue_scripts', 'custom_enqueue_cart_scripts');

However, it only works when I change the quantity for the first time. Any subsequent click is not registered. Why?


Solution

  • This is because your script event needs to be delegated to the document body and not to woocommerce selector class.

    I Added "input" event, to handle when user inputs a quantity value

    I Reduced the delay from 1000 to 500, to get something more responsive.

    So replace your PHP function and your JavaScript file, with the following :

    add_action('template_redirect', 'custom_cart_js_script');
    function custom_cart_js_script() {
        if ( ! is_cart() ) return;
        wc_enqueue_js( "var timeout; 
        $(document.body).on('change input', 'input.qty', function(){
            if ( timeout !== undefined ) clearTimeout( timeout );
            timeout = setTimeout(function() {
                $('[name=update_cart]').trigger('click'); // trigger cart update
            }, 500 );
        });" );
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works under Storefront theme.


    Similar: