jQuery .validate()submitHandler没有触发

时间:2015-06-08 22:49:40

标签: jquery jquery-validate bootbox

我正在加载一个对话框,其中包含使用Bootbox.js即时构建的表单,并且我使用jQuery验证插件验证用户输入。

验证工作正常,但在成功填写表单时会忽略submitHandler

出了什么问题?

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

请参阅下面的完整示例。我已经查看了其他类似问题的帖子。不幸的是,他们似乎在页面上呈现了表单,而我通过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>'
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

View on jsFiddle

4 个答案:

答案 0 :(得分:22)

检查jsFiddle的DOM,两个问题变得明显。

  1. 您的&#34;提交&#34; <button>type="button"

  2. 您的&#34;提交&#34;按钮位于<form></form>容器之外。

  3. 如果您希望jQuery Validate插件自动捕获&#34;提交&#34;的click事件。按钮...

    • 按钮必须是type="submit"
    • 该按钮必须位于<form></form>容器内。

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

    您还错误地将.validate()方法放置在模态对话框的success回调中&#34;提交&#34;按钮。

    .validate()方法仅用于 初始化 插件,应该被称为 一次 表单创建后。

    修改

    在解决这个问题之后,很明显Bootbox modal plugin可能会有一些严重的限制因素会干扰表单的提交。

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

    2. 我在&#34;提交&#34;中使用.valid()方法触发验证测试。

    3. 我可以初始化验证并按预期工作,但在实际表单提交之前,对话框将被取消。也许有一个解决方案,但在审查了Bootbox的文档之后,它并不是很明显。

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

      编辑2:

      根据OP的解决方案......

      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选项时没有任何错误。

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

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

答案 1 :(得分:2)

感谢Sparky的帮助,您提供的解决方案给了我答案。似乎让submitHandler对提交逻辑造成了一些混淆。

我删除了submitHandler并将以下内容添加到成功回调中,一切都按预期工作

success: {
         label: "Submit",
         className: "btn btn-sm btn-primary",
         callback: function () {
             if($("#webteamContactForm").valid()){
                    var form = $("#webteamContactForm");
                    form.submit();
                } else {
                    return false;
                }
         }
    }

答案 2 :(得分:1)

我知道这是一个老帖子,但我想我会分享我对类似问题的决心。我无法通过按Enter键让我的表单提交,但我可以在输入时验证它。所以我使用了链接方法,现在我可以在输入时提交表单。

jQuery:

  //Variables created without the keyword var, are always global, even if they are created inside a function.
    var form = $('#<?echo $PAGEID?>');
    var FormError = $('.alert-danger',form);
    var success = $('.alert-success',form);

     form.keypress(function(e){
         if(e.which == 13){ //TRIGGER SUBMIT THROUGH ENTER      
             document.getElementById('defaultActionButton').click(); 
         }
     }).validate({
        focusInvalid: false, // do not focus the last invalid input
        onkeyup: false, 
        ignore: ".ignore", //required for hidden input validation ie: hiddenRecaptcha
        rules:{
            "TYPE": {
                required: true,     
            },
            "MSG": {
                required: true,
                rangelength:[40,1000]
            },
            "CONTACT": {
                 required: {
                     depends: "#newuser:checked"
                 }
            },
            "EMAIL": {
                 required: true,
                 email: {
                    depends: function() {
                        if(!$("#newuser:checked"))
                            return true;
                        else
                            return false;
                    }
                 },
                 HTH_TelephoneEmail: {
                        depends: function() {
                            if($("#newuser:checked"))
                                return true;
                            else
                                return false;
                        }
                     }
            },          
            hiddenRecaptcha: {
                required: function () {
                    if (grecaptcha.getResponse() == '') {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        },
        messages: { // custom messages for form validation input
               "TYPE": {
                    required: 'Please select an option as it pertains to your inquiry'
               },
               "MSG": {
                    required: 'Please provide some content as it pertains to your inquiry'       
               },
               "CONTACT": {
                required: "Please enter a contact person or company"
               },
              hiddenRecaptcha: {
                required: function() {
                    $(".g-recaptcha:first").tooltip("enable").tooltip("show");
                }
              }
        },
        showErrors: function(errorMap, errorList) {
            // Clean up any tooltips for valid elements
            $.each(this.validElements(), function (index, element) {
                element = $(element);
                NoError_ToolTip(element);
            });
            // Create new tooltips for invalid elements
            $.each(errorList, function (index, error) {
                element = $(error.element);
                message = error.message;
                Error_ToolTip(element,message);
            });
        },                  
        invalidHandler: function (event, validator) { //display error alert on form submit     
            success.hide();
            $(document).scrollTop( $(".form-body").offset().top ); 
        },
         submitHandler: function () { 
       Submit_Complete(); //fires ajax call
   }
    });

答案 3 :(得分:0)

您应该更改提交按钮的名称,因为您有命名冲突。例如,尝试将其从name="submit"更改为name="other"