简体   繁体   中英

How to display a confirm box before submitting a form using jquery confirm?

I have a form and I want to show a confirmation massage after clicking submit button and also I don't want to use following method

return confirm("Are You Sure?")

I used JQuery Confirm as following.

@using (@Html.BeginForm("SubmitTest", "HydrostaticReception", FormMethod.Post, new {id="ReceptionForm", onsubmit = "ValidateMyform(this);" }))
    {
    .....
    <button onclick="SubmitMyForm()">Submit</button>
    }

The javascript codes are ...

function ValidateMyform(form) {
        // get all the inputs within the submitted form
        var inputs = form.getElementsByTagName('input');
        for (var i = 0; i < inputs.length; i++) {
            // only validate the inputs that have the required attribute
            if (inputs[i].hasAttribute("required")) {
                if (inputs[i].value == "") {
                    // found an empty field that is required
                    alert("Fill all fields");
                    return false;
                }
            }
        }
        return true;
}

The Javascript code for showing Confirm Box (According JQuery Confirm ) is

function SubmitMyForm() {
        $.confirm({
            title: 'Confirm!',
            content: 'Are you sure?',
            buttons: {
                No: function () {
                    return true;
                },
                Yes: function () {
                    $("#ReceptionForm").submit();
                    //alert("For Test");
                    //document.getElementById("ReceptionForm").submit();
                }
            }
        });
}

The Problem IS...

When I click Submit button it doesn't wait for me to click Yes button in Confirm box and the form will submit (the Confirm box appears and after 1 sec disappear and form submits).

But when I use alert("For Test"); instead of $("#ReceptionForm").submit(); , it works correctly. Does anybody knows why I'm facing this problem?!!!

You could use a "flag" to know if the confirmation occured or not to "prevent default" submit behavior.

Remove the inline onsubmit = "ValidateMyform(this);" and use a jQuery event handler instead.

var confirmed = false;
$("#ReceptionForm").on("submit", function(e){

  // if confirm == true here
  // And if the form is valid...

  // the event won't be prevented and the confirm won't show.
  if(!confirmed && ValidateMyform($(this)[0]) ){
    e.preventDefault();

    $.confirm({
      title: 'Confirm!',
      content: 'Are you sure?',
      buttons: {
        No: function () {
          return;
        },
        Yes: function () {
          confirmed = true;
          $("#ReceptionForm").submit();
        }
      }
    });
  }
});

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