JQuery.validate () submitHandler not working

I load a dialog box with a form embedded on the fly using Bootbox.js and I test the user input with the jQuery validation plugin.

Validation works just fine, but submitHandler ignored when the form completes successfully.

What will go wrong?

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

See the full example below. I looked at other posts that raised a similar issue. Unfortunately, they seem to have the form displayed on the page, while I pass mine through 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> 

View in jsFiddle

+6
source share
4 answers

DOM jsFiddle detection and two issues become apparent.

  • Your "submit" <button> is type="button" .

  • The submit button is located outside the <form></form> container.

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

  • the button should be type="submit"
  • The button should be in the <form></form> container.

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


You also incorrectly placed the .validate() method in the success callback of your submit modal dialog box.

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


EDIT

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

  • I initialize the Validate plugin after opening the dialog.

  • I use the .valid() method in "submit" to run a validation test.

I can initialize the validation and work as it should, but the dialog is rejected before the actual presentation of the form occurs. There may be a solution, but after looking at the documentation for Bootbox this is not obvious.

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


EDIT 2:

In accordance with the OP decision ...

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

However, simply by using the supplied form argument directly, you have no errors when using the submitHandler parameter of the jQuery Validate plugin.

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

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

+14
source

Thanks to Sparky for your help, the solution you provided provided me with an answer. SubmitHandler seems to cause some confusion for the send logic.

I removed submitHandler and added the following for a successful callback and everything works as expected

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

I know this is an old post, but I decided to share my solution with a similar problem. I could not get my form to submit by pressing the enter button, but I can get it to confirm when I enter. So I used the chaining method, and now I can submit my form as I type.

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 } }); 
+1
source

You must change the name for your submit button because you have a name conflict. For example, try changing it from name="submit" to name="other" .

0
source

Source: https://habr.com/ru/post/988742/


All Articles