0

How can I have I button such that onclick it creates a reCAPTCHA?

Here is what I have:

<script>
function myFunc() {
    document.getElementById("form").innerHTML = "<div class=\"g-recaptcha\" data-sitekey=\"myspecialcodewhichisasecret\"></div>";
}
</script>
<form action="/whatever" id="form" method="post">
</form>
<button onclick="myFunc()">CLICK ME AND GET FREE RECAPTCHA</button>

I am using localhost, which google says should be ok. Why doesn't the recpatcha show up when I click the button?

4
  • Did you include some JavaScript from Google? Commented Nov 15, 2015 at 0:23
  • you should include google scripts after generating the recaptcha . Commented Nov 15, 2015 at 0:25
  • I doubt it will work because you are trying to use a div that would load via automatic rendering, I assume that would occur on first load of the google script, and not whenever a DOM element is added. You will have to explicitly render the widget, or somehow re-trigger the auto-render process. Commented Nov 15, 2015 at 0:27
  • It's right there in the docs. "Explicitly render the reCAPTCHA widget": developers.google.com/recaptcha/docs/display#explicit_render using the grecaptcha.render() function. Commented Nov 15, 2015 at 0:50

1 Answer 1

2

Here's how to explicitly render the widget.

function onloadCallback() {
  document.getElementById("btn").onclick = function () {
    grecaptcha.render("form", {"sitekey": "my site key"});
  };
}
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
    async defer>
</script>
<form id="form"></form>
<button id="btn">Click</button>

Sign up to request clarification or add additional context in comments.

2 Comments

I wanted to have only one reCaptcha, not many. If you change that I'll accept.
No, vanilla javascript, the render method comes from google recaptcha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.