0

Amateur hour here.

I have an existing HTML contact form. It's not my code. This is a summarized version of it. It has an input field that is a button. There is a function defined for when the button is clicked which I believe is wrapped in a jQuery selector. This function then calls the form's submit function, also wrapped in jQuery.

$("#contact-form .submit-button").on("click", function (e) {
  $("#contact-form").submit()
}

$("#contact-form").on("submit", function (e) {
})

When I add a reCaptcha, I can provide a call back function. I want to directly call the form's submit function. I tried:

<div style="margin-top:5px;margin-bottom:15px;" id="reCaptcha" data-size="invisible" class="g-recaptcha" data-sitekey="myKey" data-callback="$(&quot;#contact-form&quot;).submit"></div>

But, it doesn't seem to do anything. I think I can add a helper function, but is there a direct way to pass the form's submit function to this reCaptcha HTML element?

Appleoddity
  • 647
  • 1
  • 6
  • 21

1 Answers1

0

This will likely give you a place to start - basically you want to trigger the submit: $("#contact-form").trigger("submit");

Here is a totally untested mockup:

$("#contact-form").on("click", '.submit-button', function(event) {
  $(event.delegateTarget).trigger('submit')
});

$("#contact-form").on("submit", function(e) {
  e.preventDefault()
  console.log('I would submit');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"></script>
<script>
  grecaptcha.ready(function() {
    //request recaptcha token; response is promise
    grecaptcha.execute('your reCAPTCHA site key here', {
        action: 'validate_captcha'
      })
      .then(function(token) {
        // add token value to form
        document.getElementById('g-recaptcha-response').value = token;
        //trigger submit
        $("#contact-form").trigger("submit");
      });
  });
</script>

<form id="contact-form">
  <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
  <input type="hidden" name="action" value="validate_captcha"> mything: <input id="my-thing" />
  <button type="submit" name="submit">Submit Me</button>
</form>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100