Google reCaptcha reset doesn't work

quarky picture quarky · May 4, 2015 · Viewed 51k times · Source

I want to reset Google reCaptcha widget when I submit my form via AJAX and have some input errors or form is sent. I'm using multiple widgets on the same page so I render these widgets explicitly.

My HTML code:

<div class="g-recaptcha" id="recaptcha-1"></div>
<div class="g-recaptcha" id="recaptcha-2"></div>
...
<div class="g-recaptcha" id="recaptcha-20"></div>

Loading widget

<script src="https://www.google.com/recaptcha/api.js?onload=reCaptchaCallback&render=explicit&hl=en" async defer></script>
<script>
    var reCaptchaCallback = function() {
        var elements = document.getElementsByClassName('g-recaptcha');
        for (var i = 0; i < elements.length; i++) {
            var id = elements[i].getAttribute('id');
            grecaptcha.render(id, {
                'sitekey' : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
            });
        }
    };
</script>

After submit form:

var id = $('.g-recaptcha', form).attr('id');
grecaptcha.reset(id);

Form is the instance of the submitted form.

Everything works fine when form is fill correctly. But reCaptcha doesn't reset or reload. It try this grecaptcha.reset() but no results.

Any idea?

Answer

levi picture levi · May 4, 2015

The grecaptcha.reset() method accepts an optional widget_id parameter, and defaults to the first widget created if unspecified. A widget_id is returned from the grecaptcha.render() method for each widget created. So you need to store this id, and use it to reset that specific widget:

var widgetId = grecaptcha.render(container);
grecaptcha.reset(widgetId);

See here.