<!-- This is adapted from django-recaptcha 4.0.0 to work on multiple
reCAPTCHA's on the same page
See verifyCaptcha_{{ widget_uuid}} for the edit #} -->
<script src="https://{{ recaptcha_domain }}/recaptcha/api.js{% if api_params %}?{{ api_params }}{% endif %}"></script>
<script type="text/javascript">
    // Submit function to be called, after reCAPTCHA was successful.
    var onSubmit_{{ widget_uuid }} = function(token) {
        console.log("reCAPTCHA validated for 'data-widget-uuid=\"{{ widget_uuid }}\"'. Submitting form...")
        document.querySelector('.g-recaptcha[data-widget-uuid="{{ widget_uuid }}"]').closest('form').submit();
    };

    // Helper function to prevent form submission and execute verification.
    var verifyCaptcha_{{ widget_uuid}} = function(e) {
        e.preventDefault();
        let myCaptcha = document.querySelector('.g-recaptcha[data-widget-uuid="{{ widget_uuid }}"]');
        let allCaptchas = document.querySelectorAll('.g-recaptcha')
        grecaptcha.execute(Array.prototype.indexOf.call(allCaptchas, myCaptcha));
    };

    // Bind the helper function to the form submit action.
    document.addEventListener( 'DOMContentLoaded', function () {
        var element = document.querySelector('.g-recaptcha[data-widget-uuid="{{ widget_uuid }}"]');
        element.closest('form').addEventListener('submit', verifyCaptcha_{{ widget_uuid}});
    });
</script>
