How to check in js that user has checked the checkbox in Google recaptcha?
Google has a call back option for when the checkbox is checked.
Add this to your form element:
data-callback="XXX"
Example:
<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="== xxxxxx =="></div>
And a disable attribute to your submit button.
Example:
<button id="submitBtn" disabled>Submit</button>
Then a create a callback function and write whatever code you need.
Example:
function recaptchaCallback() {
$('#submitBtn').removeAttr('disabled');
};
You can also call the grecaptcha object to check. grecaptcha.getResponse();
is empty when unchecked and has the verification code when checked.
grecaptcha.getResponse().length === 0
when unchecked
function isCaptchaChecked() {
return grecaptcha && grecaptcha.getResponse().length !== 0;
}
if (isCaptchaChecked()) {
// ...
}
To check if google recaptcha is checked or not you can do it by the following code :
<script>
if(grecaptcha && grecaptcha.getResponse().length > 0)
{
//the recaptcha is checked
// Do what you want here
alert('Well, recaptcha is checked !');
}
else
{
//The recaptcha is not cheched
//You can display an error message here
alert('Oops, you have to check the recaptcha !');
}
</script>
To check if google recaptcha v2 is checked or not you can do it by the following code :
var checkCaptch = false;
var verifyCallback = function(response) {
if (response == "") {
checkCaptch = false;
}
else {
checkCaptch = true;
}
};
$(document).ready(function() {
$("#btnSubmit").click(function() {
if (checkCaptch && grecaptcha.getResponse()!="") {
//Write your success code here
}
});
})