将表单onsubmit参数与jquery提交事件处理程序结合起来 [英] Combining form onsubmit parameter with jquery submit event handler

查看:122
本文介绍了将表单onsubmit参数与jquery提交事件处理程序结合起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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

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.

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

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

问题在于表单的 onsubmit 参数会首先触发,然后运行 check_theForm(),然后是 $('#theForm').submit(函数(event)处理程序将触发,最终运行 $('#theForm').unbind('submit').submit(); ,此时 check_theForm()第二次运行.如果出现表单错误,这些错误现在将显示两次.

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.

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

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?

推荐答案

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

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

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

allowing you full control without your own event handler.

在这种情况下,给出:

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

这篇关于将表单onsubmit参数与jquery提交事件处理程序结合起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆