简体   繁体   中英

Show Confirm Alert Box before submitting the PHP Form

<script type="text/javascript">

var validate = (function() {
  var reClass = /(^|\s)required(\s|$)/;  // Field is required
  var reValue = /^\s*$/;                 // Match all whitespace


  return function (form) {
    var elements = form.elements;
    var el;
    var amount = document.forms["myForm"]["amount"].value;
    var quantity = document.forms["myForm"]["quantity"].value;

    for (var i=0, iLen=elements.length; i<iLen; i++) {
      el = elements[i];

      if (reClass.test(el.className) && reValue.test(el.value)) {
        // Required field has no value or only whitespace
        // Advise user to fix
        alert('Please fix ' + el.name);
        return false;
      }

    }
    if (amount == null || amount == "" || isNaN(amount)) {
        alert("Total Amount must be only numbers");
        return false;
    } 
    else if (quantity == null || quantity == "" || isNaN(quantity)) {
        alert("Quantity must be only numbers");
        return false;
    }
   else{
    confirm("Confirm Order Submission ?");

}

  }
}());

</script>

This is a form validation script using "required" id for mandatory input fields which is working fine. I just want a confirm alert box after the last else if statement which I tried using confirm() but the form is still getting submitted even when I click on "Cancel"

else{
    if (confirm("Confirm Order Submission ?")) return true;
    else return false;       
    }

This made it work !

 <!DOCTYPE html> <html> <body> <p>Click the button to display a confirm box.</p> <button onclick="myFunction()">Try it</button> <script> var x; function myFunction() { x = confirm("Press a button!"); alert(x) if(x === true){ alert("Call Submit !!!!"); }else{ alert("Don't Call Submit !!!!"); } } </script> </body> </html> 

Try this code from w3school Display a confirmation box

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_confirm

The confirm() method returns true if the user clicked "OK", and false otherwise.

Refer to https://www.w3schools.com/jsref/met_win_confirm.asp you can use confirm() method.

var txt;
var r = confirm("Press a button!");
if (r == true) {
    txt = "You pressed OK!";
    // Continue submit the form
} else {
    txt = "You pressed Cancel!";
    // Do nothing or return to form
} 

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