Cartoon of Author

@zackeryfretty

Run a JavaScript function when the WooCommerce Cart updates

🗓

I needed to run a JS function whenever someone updated the products in the WooCommerce cart while on the cart page itself -- either by clicking "Update Cart" or by hitting enter after changing the quantity of an item in the cart.

My first approach to this was to just hook the function on the "submit" event for form.woocommerce-cart-form - but - ran into an issue as this only worked when someone clicked the "Update Cart" button but not if they were to submit using a keypress.

I tried digging around WooCommerce's trigger() events to find something that would work here but didn't have any luck, so I took a peek at the frontend/cart.js file and noticed that WooCommerce seems to be handling it like so...

jQuery(document).on('click','.woocommerce-cart-form :button[type=submit]',yourFunctionHere);
jQuery(document).on('keypress','.woocommerce-cart-form :input[type=number]',yourFunctionHere);

Simply replace yourFunctionHere with the name of your function and you should be good to go, at the time of writing this seems to be working for me as expected.

Hopefully that helps someone out! I spent more time than I would have liked digging around for that, especially when I thought it would just be a simple submit event...😅

———