简体   繁体   中英

Jquery code to show modal after form validation is done

Following on from this question: Previous question

I have form validation on my form, which needs to be validated first ie minimum characters and numbers etc.

My Jquery code so far shows the modal after the submit button is pressed and the form has some input in there but not the valid input, so I just need to type a few characters and the modal pops up which is not ideal.

So I need the form to have input and validate then the modal pops up and the user has to accept terms and conditions then they can register.

I have tried the following with no luck:

$(document).ready(function() {
  $("#login-form").submit.valid(function(e) {
    e.preventDefault();
    $(".modal").addClass("active");
  });
});

Thanks in advance

You should use an if inside your submit event:

$("#login-form").submit(function(e) {
  e.preventDefault();
  if ($(this).valid()) {            // this assumes you are using something like jquery validate - from  your original code, it looks like you were attempting to do this
    $(".modal").addClass("active");
  } else {
    // do error stuff here
  }
});

Why use valid? jQuery valid() does not accept any arguments, only returns true. Use validate() instead to use handler.

$("#yourform").validate({
  submitHandler: function(form) {
    // ...
    form.submit();
  }
});

you can do this on your form...

<form id="myform" action=".." method=".." onsubmit="return validateForm(this);"> 
.....
</form>

then in your script you define the validate(this) function which receives the form object(this). now lets assume you are using the jquery form validation plugin

function validate(formObj){
  v = $(formObj).validate({ // initialize the plugin
        rules: {  //enter additional rules.
           input1: {required: true, email:true},   
           input2: {required: true, integer:true}
        },
        submitHandler: function(formObj) {
          $('#myform').removeAttr('onsubmit');   //remove the onsubmit attr..              
          $(modal).addClass('active');    //then show the modal here.. 

        }
      });
  return false; //which stops the form from submitting.. 
}

now lets assume the modal has popped up and the user has accepted the agreement and clicked on the agree button, which then triggers the form and sends it

function sendFromModal(){
  $('#myform').submit();
   return true; //
}

this should work, i hope i was helpful enough..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM