将表单onsubmit参数与jquery提交事件处理程序结合起来

时间:2019-10-15 15:13:11

标签: jquery forms event-handling onsubmit recaptcha-v3

我有一个由旧版后端代码生成的表单,由于多种原因,我无法更改。表单是简单的HTML:

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

提交后,将使用onsubmit函数(其中包含“普通香草” javascript)(即没有jQuery代码)触发check_theform()参数以验证是否已填写所有必填字段。换句话说,基本的东西。

我现在正尝试通过添加以下内容来向此表单添加reCAPTCHA V3:

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

问题在于,表单的onsubmit参数首先被触发,并运行check_theForm(),然后$('#theForm').submit(function(event)处理函数被触发,并最终在{{1} 1}}再次运行。如果存在表单错误,这些错误现在将显示两次。

如何在不更改表单的HTML代码或$('#theForm').unbind('submit').submit();的情况下防止这种重复,因为它们是由我无法更改的旧版后端代码生成的?

1 个答案:

答案 0 :(得分:1)

拥有onsubmit="x()"后,您可以使用

删除html onsubmit处理程序
$("#id").attr("onsubmit", null);

允许您完全控制自己的事件处理程序。

在这种情况下,给出:

$("#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();
      });;
  });
});
相关问题