How to run JavaScript function in WooCommerce checkout?

I’m building reCAPATCHA into my WooCommerce checkout. It is a fairly easy process as I’m using woocommerce_checkout_process to validate the capatcha. However, I have running into one issue.

When there is a cart error, I want to be able to reset the reCAPATCHA using grecaptcha.reset(); JavaScript function. I’m unsure how to run the JavaScript command upon cart error in WooCommerce. Any tips?

Thanks!

2 Answers
2

I had exactly the same need, because of the ajax checkout validation.

Woocommerce has some custom javascript events we can hook to.
In reCaptcha specific case we need to hook to checkout_error that is triggered when the ajax call fails.

So, I solved with the following code in my own javascript file, besides the PHP custom validation hooked to woocommerce_checkout_process:

jQuery(document).ready(function($) {
    $( document.body ).on( 'checkout_error', function() {
        grecaptcha.reset();
    });
});

Hope it helps.

Leave a Comment