Combining form onsubmit parameter with jquery submit event handler

China☆狼群 提交于 2021-02-11 16:20:19

问题


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?


回答1:


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();
      });;
  });
});


来源:https://stackoverflow.com/questions/58397882/combining-form-onsubmit-parameter-with-jquery-submit-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!