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?
For reCaptcha v2, use: grecaptcha. reset();
reset(recaptcha2); To be clear, you have to save the return values of grecaptcha. render(), and pass in those vars to the reset() function. Passing in the string ID of the captcha doesn't work.
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.
You are passing the wrong id.
$('.g-recaptcha', form).attr('id');
Your selector will capture all 20 reCaptcha widget, but only return a single DOM id (the first reCaptcha). So your code is actually resetting the first recaptcha.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With