I'm adding ReCAPTCHA to a (Bootstrap Jekyll) website that has multiple contact forms. There's a popup modal in the footer, an occasional "contact us now" section, and also a "request more information about ____" on several pages.
Since I have multiple contact forms on a single page, I needed to explicitly render each ReCAPTCHA. Here's the code for that:
In my javascript:
var CaptchaCallback = function() {
grecaptcha.render('RecaptchaField1', {'sitekey' : 'my_sitekey'
});
grecaptcha.render('RecaptchaField2', {'sitekey' : 'my_sitekey'
});
};
In footer (included on all pages)
<div id="RecaptchaField1"></div>
(and at the bottom of the footer)
<script src='https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit' async defer></script>
This works well on a page that has two separate contact forms (i.e. I've got another div on the page with the id of RecaptchaField2), but if I land on a page that only has one contact form, the console throws an error (Uncaught Error: ReCAPTCHA placeholder element must be an element or id).
The ReCAPTCHA seems to work anyway, but can anyone help me understand what's causing this error? All the research I've done indicates that it's from importing the library twice, but I'm assuming that's not the case, since the problem only comes up on some pages and not others.
Thank you!
This works for me:
var CaptchaCallback = function() {
if ( $('#RecaptchaField1').length ) {
grecaptcha.render('RecaptchaField1', {'sitekey' : 'my_sitekey'
});
}
if ( $('#RecaptchaField2').length ) {
grecaptcha.render('RecaptchaField2', {'sitekey' : 'my_sitekey'
});
}
};