jQuery .validate()SubmitHandler不触发 [英] jQuery .validate() submitHandler not firing

查看:100
本文介绍了jQuery .validate()SubmitHandler不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在加载一个对话框,该对话框使用 Bootbox.js 即时构建我正在使用jQuery验证插件来验证用户输入.

I'm loading a dialog box with a form that's built on-the-fly using Bootbox.js and I'm validating user input with a jQuery validate plugin.

验证工作正常,但是成功填写表单后,将忽略submitHandler.

Validation works just fine, but the submitHandler is ignored when the form is filled in successfully.

怎么了?

submitHandler: function(form) {
    alert("Submitted!");
    var $form = $(form);
    $form.submit();
}

请参阅下面的完整示例.我看过其他引发类似问题的帖子.不幸的是,他们似乎在页面上呈现了表单,而我是通过jQuery呈现的.

See the full example below. I've looked at other posts where a similar issue has been raised. Unfortunately they seem to have the form rendered on the page whereas I'm rendering my via jQuery.

$(document).on("click", "[data-toggle=\"contactAdmin\"]", function() {
  bootbox.dialog({
    title: "Contact admin",
    buttons: {
      close: {
        label: 'Close',
        className: "btn btn-sm btn-danger",
        callback: function() {}
      },
      success: {
        label: "Submit",
        className: "btn btn-sm btn-primary",
        callback: function() {
          $("#webteamContactForm").validate({
            rules: {
              requestType: {
                required: true
              }
            },
            messages: {
              requestType: {
                required: "Please specify what your request is for",
              }
            },
            highlight: function(a) {
              $(a).closest(".form-group").addClass("has-error");
            },
            unhighlight: function(a) {
              $(a).closest(".form-group").removeClass("has-error");
            },
            errorElement: "span",
            errorClass: "help-blocks",
            errorPlacement: function(error, element) {
              if (element.is(":radio")) {
                error.appendTo(element.parents('.requestTypeGroup'));
              } else { // This is the default behavior 
                error.insertAfter(element);
              }
            },
            submitHandler: function(form) {
              alert("Submitted!");
              var $form = $(form);
              $form.submit();
            }
          }).form();
          return false;
        }
      }
    },
    message: '<div class="row">  ' +
      '<div class="col-md-12"> ' +
      '<form id="webteamContactForm" class="form-horizontal" method="post"> ' +
      '<p>Please get in touch if you wish to delete this content</p>' +
      '<div class="form-group"> ' +
      '<div class="col-md-12"> ' +
      '<textarea id="message" name="message" class="form-control input-md" rows="3" cols="50">This email is to notify you the creator is putting a request for the following item\n\n' +
      this.attributes.getNamedItem("data-url").value + '\n\n' + '</textarea> ' +
      '<span class="help-block">Feel free to change the message and add more information. Please ensure you always provide the link.</span> </div> ' +
      '</div> ' +
      '<div class="form-group requestTypeGroup"> ' +
      '<label class="col-md-4 control-label" for="requestType">This request is for:</label> ' +
      '<div class="col-md-4"> <div class="radio"> <label for="Edit"> ' +
      '<input type="radio" name="requestType" id="requestType-0" value="Edit"> ' +
      'Editing </label> ' +
      '</div><div class="radio"> <label for="Delete"> ' +
      '<input type="radio" name="requestType" id="requestType-1" value="Delete"> Deletion</label> ' +
      '</div> ' +
      '</div> </div>' +
      '</form> </div>  </div>'
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"></script>

<a data-toggle="contactAdmin" data-title="help" data-url="http:/www.mydomain.com/some-url" href="#">Contact Web team</a>

在jsFiddle上查看

推荐答案

检查jsFiddle的DOM,两个问题显而易见.

Inspecting the DOM of the jsFiddle and two problems become apparent.

  1. 您的提交" <button>type="button".

您的提交"按钮在<form></form>容器之外.

Your "submit" button is outside of the <form></form> container.

如果您希望jQuery Validate插件自动捕获提交"按钮的click事件...

If you want the jQuery Validate plugin to automatically capture the click event of the "submit" button...

  • 该按钮必须为type="submit"
  • 该按钮必须在<form></form>容器内.
  • the button must be a type="submit"
  • The button must be within the <form></form> container.

如果您希望插件按预期运行,则必须满足这两个条件.

These two conditions must be met if you want the plugin to operate as intended.

您还将.validate()方法错误地放置在模式对话框提交"按钮的success回调中.

You've also incorrectly placed the .validate() method within the success callback of your modal dialog box "submit" button.

.validate()方法仅用于 初始化 插件,并且在表单已创建.

The .validate() method is only used for initializing the plugin and should be called once after the form is created.

编辑:

在解决了这个问题之后,很明显 Bootbox模态插件可能有一些关键限制,会干扰提交的形式.

After playing around with this, it becomes apparent that the Bootbox modal plugin may have some critical limitations that interfere with the submission of the form.

  1. 在对话框打开后,我正在初始化Validate插件.

  1. I am initializing the Validate plugin after the dialog is opened.

我正在提交"中使用.valid()方法来触发验证测试.

I am using the .valid() method within the "submit" to trigger the validation test.

我可以初始化验证并按预期进行工作,但是在实际提交表单之前,将关闭该对话框.也许有解决方案,但是在查看了Bootbox的文档之后,还不很清楚.

I can get validation initialized and working as it should, but the dialog is dismissed before the actual form submission takes place. Perhaps there is a solution, but after reviewing the documentation for Bootbox, it's not readily apparent.

https://jsfiddle.net/vyaw3ucd/2/

根据OP的解决方案...

As per the OP's solution...

bootbox.dialog({
    // other options,
    buttons: {
        success: {
            label: "Submit",
            className: "btn btn-sm btn-primary",
            callback: function () {
                if ($("#webteamContactForm").valid()) {
                    var form = $("#webteamContactForm");
                    form.submit();  // form submits and dialog closes
                } else {
                    return false;  // keeps dialog open
                }
            }
        }
    }
});

但是,通过直接使用提供的form参数,使用jQuery Validate插件的submitHandler选项时,您不会出现任何错误.

However, by simply using the supplied form argument directly, you do not have any errors when using the submitHandler option of the jQuery Validate plugin.

submitHandler: function (form) {
    console.log("Submitted!");
    form.submit();
}

演示: https://jsfiddle.net/vyaw3ucd/5/

DEMO: https://jsfiddle.net/vyaw3ucd/5/

这篇关于jQuery .validate()SubmitHandler不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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