What is the name of the domain?
none
What is the error number?
none
What is the error message?
none
What is the issue you’re encountering
how to do it
What are the steps to reproduce the issue?
Hi everyone!
I am working with Cloudflare’s Turnstile CAPTCHA on a page with multiple forms, and I need to disable the submit button until the user successfully completes the CAPTCHA challenge. Once the user solves the CAPTCHA, the button should be enabled. However, I encountered some issues trying to handle multiple forms on the same page.
How can I listen to a passed event ?
My Code so far:
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback" defer></script>
<script>
// This function is called when the Turnstile script is loaded and ready to be used.
// The function name matches the "onload=..." parameter.
window.onloadTurnstileCallback = () => {
const formsWithTurnstile = document.querySelectorAll('form:has(.cf-turnstile)');
console.debug('_turnstileCb called', {formsWithTurnstile});
// Disable submit buttons for all forms initially
formsWithTurnstile.forEach(function(form) {
const submitButton = form.querySelector('button[type="submit"]');
if (submitButton) {
submitButton.disabled = true; // Disable button initially
}
// Listen for Turnstile pass event to enable the submit button
const turnstileElement = form.querySelector('.cf-turnstile');
if (!turnstileElement) {
return;
}
turnstile.render('#' + turnstileElement.id, {
sitekey: '1x00000000000000000000AA',
theme: 'light',
dataSize: "flexible"
});
// Add event listener for the 'turnstile:pass' event
turnstileElement.addEventListener('turnstile:pass', function() {
console.log('Turnstile passed, enabling submit button');
if (submitButton) {
submitButton.disabled = false; // Enable the submit button when the user passes the CAPTCHA
}
});
});
}
</script>