Search code examples
jqueryformsevent-handlingonsubmitrecaptcha-v3

Combining form onsubmit parameter with jquery submit event handler


I have a form that is being generated by legacy back-end code that, for a variety of reasons, I can't change. The form is straightforward HTML:

<form action="#" id="theForm" onsubmit="return check_theForm(); method="post">
  <!-- fields go here -->
</form>

On submission the onsubmit parameter fires to verify that all compulsory field have been filled in, using the check_theform() function which contains "plain vanilla" javascript (i.e. no jQuery code). In other words, basic stuff.

I'm now trying to add reCAPTCHA V3 to this form by adding the following:

$('#theForm').submit(function(event) {
  event.preventDefault();
  grecaptcha.ready(function() {
    grecaptcha.execute('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
      {action: 'contactForm'}).then(function(token) {
        $('#theForm').prepend('<input type="hidden" name="token" value="' + token + '">');
        $('#theForm').prepend('<input type="hidden" name="action" value="contactForm">');
        $('#theForm').unbind('submit').submit();
      });;
  });
});

The problem is that the form's onsubmit parameter fires first, which runs check_theForm(), and then the $('#theForm').submit(function(event) handler fires, which eventually runs $('#theForm').unbind('submit').submit(); at which point check_theForm() runs a second time. If there are form errors, these are now being displayed twice.

How can I prevent this duplication without making changes to the form's HTML code or to check_theForm(), seeing as these are generated by legacy back-end code that I can't change?


Solution

  • When you have onsubmit="x()" you can remove the html onsubmit handler with

    $("#id").attr("onsubmit", null);
    

    allowing you full control without your own event handler.

    In this case, giving:

    $("#theForm").attr("onsubmit", null);
    
    $('#theForm').submit(function(event) {
      event.preventDefault();
      grecaptcha.ready(function() {
        grecaptcha.execute('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
          {action: 'contactForm'}).then(function(token) {
            $('#theForm').prepend('<input type="hidden" name="token" value="' + token + '">');
            $('#theForm').prepend('<input type="hidden" name="action" value="contactForm">');
            if (check_theForm())
                $('#theForm').unbind('submit').submit();
          });;
      });
    });