Posted on

WooCommerce: Automatically Update Cart on Quantity Change

There is a lot of literature online that solves this UX problem – so in this article let’s see if I can give you a simplified, working, updated version.

So, do you hate the “Update Cart” button too? Yes, the one you have to click after you update the quantity of a product in the cart…

Well, you’re in the right place: a simple PHP function, two lines of JQuery, one line of CSS and the result is pretty straight forward!

Automatically update the WooCommerce Cart when the quantity changes

Part 1 – CSS Snippet: Hide the WooCommerce “Update Cart” Button

First of all we need to hide the button, as we’re not going to use it at all and let PHP and JQuery do the magic instead. I know !important is not a great thing to have in your CSS code… but for this time we’ll keep it simple.


input[name='update_cart'] {
display: none !important;
}

/* OR TRY THIS */

button[name='update_cart'] {
display: none !important;
}

Part 2 – PHP Snippet: Auto-update WooCommerce Cart when Quantity Changes

Now that the button is hidden, all we need to do is to “click” the button via JQuery and let WooCommerce do the exact same job (updating cart totals, taxes, etc.).

In detail, when we “click” on any of the quantity inputs, we go and trigger a “click” on the hidden Update Cart button.

Easy, no?


/**
 * @snippet       Automatically Update Cart on Quantity Change - WooCommerce
 * @how-to        Watch tutorial @ https://businessbloomer.com/?p=19055
 * @sourcecode    https://businessbloomer.com/?p=73470
 * @author        Rodolfo Melogli
 * @compatible    Woo 3.5.1
 */

add_action( 'wp_footer', 'bbloomer_cart_refresh_update_qty' ); 

function bbloomer_cart_refresh_update_qty() { 
	if (is_cart()) { 
		?> 
		<script type="text/javascript"> 
			jQuery('div.woocommerce').on('click', 'input.qty', function(){ 
				jQuery("[name='update_cart']").trigger("click"); 
			}); 
		</script> 
		<?php 
	} 
}

Where to add this code?

You can place PHP snippets at the bottom of your child theme functions.php file (before "?>" if you have it). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such delicate files - if you need more guidance, please take a look at my free WooCommerce Customization video tutorial.

Does this snippet still work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7.

If you think this code saved you time & money, please join other Business Bloomer supporters and avail of 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce?

Check out these free videos, tutorials and tips!

  • how-to-edit-woocommerce-with-php-snippets
  • woocommerce-hooks-add_action-list-visual
  • woocommerce-customize-single-product-page-PHP
  • woocommerce-customize-shop-page-PHP
  • woocommerce-advanced-customization
  • how-to-edit-woocommerce-cart
  • woocommerce-customize-checkout-page-PHP
  • woocommerce-email-customization
  • woocommerce-conditional-logic

Rodolfo Melogli

Author, WooCommerce expert, WordCamp speaker and Internet marketer, Rodolfo Melogli has worked as a WooCommerce freelancer since 2011. He helps entrepreneurs and developers overcome their WooCommerce nightmares :) Rodolfo is the organiser of WordCamp Dublin, the Dublin WooCommerce Meetup, the Dublin Ecommerce Meetup and the Dublin WordPress Meetup. He enjoys interacting with people, travelling and chasing tennis & soccer balls. Of course, he loves pizza too.

54 thoughts on “WooCommerce: Automatically Update Cart on Quantity Change

  1. Hi again Rodolfo.
    Once again thx for your help.

    As i mentioned to you earlier. Your code above does not work for quantity with +/- selectors.
    However, a little twist will also make your code work for that as well:

    add_action( 'wp_footer', 'bbloomer_cart_refresh_update_qty' );
    
    function bbloomer_cart_refresh_update_qty() {
        if (is_cart()) {
            ?&gt;
            
            jQuery('div.woocommerce').on('change', 'input.qty', function(){
                setTimeout(function() {
                    jQuery('[name="update_cart"]').trigger('click');
                }, 100 );
            });
            
            &lt;?php
        }
    }
    
    1. Nice, thank you πŸ™‚

  2. cool snippet Rodolfo.
    However, this only works when actually clicking inside the quantity input. I can’t make it work when clicking the decrease or increase (+/-) signs.

  3. Another CSS code to hide button that works with my theme:

    button[name=”update_cart”] {
    display: none !important;
    }

    1. Thank you πŸ™‚

  4. Your solution didnt work( even gave a 500 error) But JOS’s solution from july is perfect. Please update it

  5. Hi,
    Thanks for the code, works nicely, with one caveat. css snippet has input[name=’update_cart’] but in my case (version 3.5.1) it works with button[name=’update_cart’]
    Take care
    Can

    1. Thanks!

  6. This code really helpful for me thanks.

    1. Nice πŸ™‚

  7. Great code!

    I need to set it to another class, but then it only works once. How come? And how to fix that?

     
    jQuery('.woocommerce-cart-form').on('change', 'input.qty', function(){ 
    

    Thanks!

    1. Hey Peps – thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  8. Hi.

    It’s an useful topic for me as I am creating an eCommerce Store. I am using ‘WHOLESALE MARKET’ Plugin from “Cedcommerce”. As per your Instant Price Update, I want to update the price instantly when the quantity reaches its Minimum Order of quantity. It can not update for each increament of quantity as you said. So can you give me what code and where should i insert?

    1. Hello Jonn, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  9. Hey, your code did not work for me πŸ™ This one, instead, works like a charm (found on stack exchange)

    add_action( 'wp_footer', 'cart_update_qty_script' );
    function cart_update_qty_script() {
        if (is_cart()) :
            ?&gt;
            
        jQuery('div.woocommerce').on('change', '.qty', function(){
        jQuery("[name='update_cart']").prop("disabled", false);
            jQuery("[name='update_cart']").trigger("click"); 
        });
        
            &lt;?php
        endif;
    }
    
    1. Thanks Cam πŸ™‚

  10. If I may suggest an update, if you set a timeout variable it doesn’t jump on every click. Example:

    
    add_action( 'wp_footer', 'bbloomer_cart_refresh_update_qty' ); 
    
    function bbloomer_cart_refresh_update_qty() { 
    	if (is_cart()) { 
    		?&gt; 
         
          var timeout;
    			jQuery('div.woocommerce').on('click', 'input.qty', function(){ 
            if(timeout != undefined){
              clearTimeout(timeout);
            }
            timeout = setTimeout(function() {
              jQuery("[name='update_cart']").trigger("click"); 
            }, 500);
    			}); 
    		 
    		&lt;?php 
    	} 
    }
    
    
    1. Very nice, thanks a lot MartΓ­ πŸ™‚

    2. I made some changes:
      – Update after 2 seconds (our customers aren’t faster than that πŸ™‚ )
      – Update on changes with keyboard as well
      – Don’t update if the value is empty

      add_action( 'woocommerce_after_cart', function() {
      	?>
      		<script>
      			jQuery(function($) {
      				var timeout;
      				$('div.woocommerce').on('change textInput input', 'form.woocommerce-cart-form input.qty', function(){
      					if(typeof timeout !== undefined) clearTimeout(timeout);
      
      					//Not if empty
      					if ($(this).val() == '') return;
      
      					timeout = setTimeout(function() {
      						$("[name='update_cart']").trigger("click"); 
      					}, 2000);
      				}); 
      			});
      		</script>
      	<?php
      } );
      
    3. AWESOME! Thanks Jos πŸ™‚

  11. Hi, nice trick, very helpful for me, but I found two issues and solved it as follows:
    —> replace input[name=’update_cart’] to: button[name=’update_cart’];
    —> button[name=’update_cart’] is disabled by default and it is necessary to enable it when window is loaded and cart is updated:

    jQuery(window).on('load', function(){
        jQuery("[name='update_cart']").removeAttr('disabled');
    });
    jQuery( document.body ).on( 'updated_cart_totals', function(){
        jQuery("[name='update_cart']").removeAttr('disabled');
    );
    
    1. Thanks Agata, I’d say this is very much theme-dependent. Cheers πŸ™‚

  12. Hello need add setTimeout to correct work with all themes http://prntscr.com/jsiy12

    1. Nice tip, let’s see if it helps anyone. Thanks πŸ™‚

    2. This worked for me, thank you @Wayheming and @Rodolfo!

    3. πŸ™‚

  13. Did not work on the cart page, works on the Single product page.

    1. Sorry, the hide did not work. Rest of it worked.

    2. Thanks Ibrahim! You might have to change the input name the JQuery targets, take a look πŸ™‚

  14. Hi Rodolfo,
    Great snippet, works like a charm on pc!
    Is it also supposed to work on mobile, or it is only me?
    My theme is storefront.
    Many thanks!

    1. Hey Kostas, thanks for your message! It should work well on mobile as well, however I did not test it. It could be that the CSS classes and HTML tags I target in the PHP change for mobiles, so the code *might* need to be adjusted. Give it another go and let me know

  15. After latest WordPress 4.9.6 and WooCommerce 3.4 update I get a tooltip notice on Chrome “Please match the format requested” http://prntscr.com/jm3t18 and it doesn’t work

    1. Hey Michal, thanks for your comment! I just tested this again with Storefront theme and it works perfectly. Maybe your theme (or another plugin) is messing/conflicting with my snippet?

      To troubleshoot, go to WP Dashboard > WooCommerce > System Status: what errors do you see in red font?

      Also, take a look at this tutorial to see how to troubleshoot: https://businessbloomer.com/woocommerce-troubleshooting-mistakes-to-avoid/

      Finally, can you try switching temporarily to “Twentyseventeen” or “Storefront” theme and let me know if it works?

      Hope this helps!

      R

  16. The only addendum I’d like to add is for theme individuality…

    Some themes only have a button to update the cart, so, a little editing of the css is helpful:

    /** hide update cart button if function used */
    input[name=’update_cart’], button[name=’update_cart’] {
    display: none !important;
    }

    this will hide either/or both the input, and a buuton if used by a theme.

    1. Cool thanks Roberta πŸ™‚

  17. Hi, this works well, only I need the plus & minus buttons also update the cart in the same way it does when inputting the number in the box. Would it be possible?

    Many thanks πŸ™‚

    1. Arus, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  18. This snippet is ideal for me but any idea why it would only work on every second change?

    1. Naomi, thanks for your comment! Uhm, no idea, maybe there is a jQuery conflict specific to your theme/plugins πŸ™‚

    2. I have the same issue. I am using Flatsome theme. Is there a way to troubleshoot jQuery conflicts?

    3. Hey Sanya / Naomi! If the Jquery works on another theme such as 2017, then there is a problem with Flatsome (bug). In this case, it might be worth it contacting their support team πŸ™‚

    4. It’s because the β€œupdate cart” button is disabled at the beginning, only when input is changed then it becomes active.
      Add one line and it should work πŸ™‚

      jQuery(‘div.woocommerce’).on(‘change’, ‘input.custom-qty’, function(){
      jQuery(“[name=’update_cart’]”).removeAttr(‘disabled’);
      jQuery(“[name=’update_cart’]”).trigger(“click”);
      });

      @rodolfo please ignore my previous comments and leave only that one πŸ˜‰

    5. Maybe an onChange event, to the qty field would work – so if a user uses either the plus & minus buttons, or types in an quantity amount change, it responds to the event?

  19. Hello Rodolfo,
    First of all, nice snippets, very helpful.
    I’m living near Valencia, Spain, so have a nice tryp over there.
    I just wanted to say that I’ve tried this snippet, but it doesn’t works.
    Maybe it’s because of the new update of woocommerce.
    Thank you again.

    1. Thank you Stan! Could you try the snippet on a different theme please e.g. 2017?

  20. Hello Rodolfo.

    First of all thank you for the idea. It works as expected. The only problem I see with it, is that when you click on the normal “Update Cart” button, there goes a whole process that takes a second or two. The same happens with the JQuery snippet you included and of course, it is expected, as it is only clicking for us. But if the customer has many different items in cart and wish to edit the whole order before checking out, he or she will find him or her self waiting on each number changed until quantities are as expected. On the old fashion way (button), you change all the numbers you want to and then the button is clicked and you only wait once.

    Nothing wrong with your snippet, in fact, it is an excellent idea for stores that mostly sell one or few items and there will always be only one or a few items in a cart at the same time. The problem is that WooCommerce lacks simplicity in the amount updating routine, like for example, when I shop in AliExpress, you pick an item, click on “+” or “-” symbol in “Quantity” and the dollars amount is updated instantly. Not even the waiting symbol shows. Maybe WooCommerce looks at too many things at the same time when cart is updated, like tax, availability, etc. etc., which introduces the a lag in the output.

    Thanks again for all your simple, but helpful and brilliant ideas.

    Richard

    1. Thanks for your comment Richard! I’m sure WooCommerce is looking into this for future developments πŸ™‚

  21. Suggestion.

    Changing this line:

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

    to:

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

    will still allow updating the quantity via keyboard.

    1. @Metal Guru no you need to wait every time from changing for example from 5 to 1

  22. That’s a very clever solution. I was expecting you to disable the “Update Cart” button via a template change and then trigger the ajax call to update the cart.

Questions? Feedback? Support? Leave your Comment Now!
If you're writing code, please wrap it between: [php] code_here [/php]

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.