I'm working on a function which requires doing a reCaptcha verification within a SweetAlert popup box, but I'm getting the following error:
Uncaught Error: reCAPTCHA placeholder element must be an element or id
I've been looking into what's causing this error, and I notice it's because the element hasn't been loaded yet when it tries to generate the reCaptcha element.
function confirmBox() {
var div = document.createElement('div');
div.id = 'recaptcha';
div.onload = genRecaptcha();
swal({
title: "Are you sure?",
content: div,
icon: "warning",
buttons: true,
dangerMode: true,
})
}
function genRecaptcha() {
console.log($('#recaptcha').attr('id'));
grecaptcha.render('recaptcha', {
'sitekey': '6Le2ZFUUAAAAAEV4IM_5weEnXg4gVplan2Atgiaj'
});
}
$('#btn1').click(confirmBox);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<button id="btn1">Submit</button>
I'm trying to put the genRecaptcha
function with the onload
trigger, but it seems to be unable to get the element.
Is there any way to execute the function after the popup box is fully loaded? Or there is something I did wrong here?
Problem solve by using $(element).ready
from jquery instead of using .onload
code snippet provided below won't able to function properly because of the recaptcha site key is invalid for this site
function confirmBox() {
var div = document.createElement('div');
div.id = 'recaptcha';
$('#recaptcha').ready(function () {
console.log($('#recaptcha').attr('id'));
grecaptcha.render('recaptcha', {
'sitekey': '6Le2ZFUUAAAAAEV4IM_5weEnXg4gVplan2Atgiaj'
});
})
swal({
title: "Are you sure?",
content: div,
icon: "warning",
buttons: true,
dangerMode: true,
})
}
$('#btn1').click(confirmBox);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<button id="btn1">Submit</button>