JEP
JEP

Reputation: 39

trigger jquery modal popup on form submit

This is my first time working with jquery modals. I'm trying to display the popup only when the form is submitted. But instead, it's displaying on page load. How do I fix it?enter image description here

 <script>

  $( function() {
    $( "#dialog-confirm" ).dialog({
  resizable: false,
  height: "auto",
  width: 400,
      modal: true,
      buttons: {
        "Yes": function() {
          $( this ).dialog( "close" );
        },
        "No": function() {
          $( this ).dialog( "close" );
        }
      }
    });
  } );


  </script>


<div id="dialog-confirm" title="Not so fast">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 
20px 0;"></span>Did you want to add a third for only $50? Click Yes to add</p>
</div>

<form id="orderform" action="/action_page.php">
  Package 1:<br>
  <input type="text" name="packageonename" value="">
  <br>
  Package 2:<br>
  <input type="text" name="packagetwoname" value="">
  <br><br>
  <input type="submit" value="Submit">
</form>  

Upvotes: 0

Views: 3961

Answers (2)

dilusha_dasanayaka
dilusha_dasanayaka

Reputation: 1441

You can do like this

$('#orderform').submit(function() {

    $("#dialog-confirm").dialog("open");
    return true; // return false to cancel form action
});

Upvotes: 0

Nisarg Shah
Nisarg Shah

Reputation: 14531

In order to prevent the dialog from automatically opening you can set autoOpen property to false when initializing the dialog.

Then, on form's submit event, you could open the dialog by calling element.dialog("open").

Note that I have added an event.preventDefault() in the submit event handler to prevent the form from submitting.

$(function() {
  $("#dialog-confirm").dialog({
      resizable: false,
      height: "auto",
      width: 400,
      modal: true,
      autoOpen: false,
      buttons: {
        "Yes": function() {
          $(this).dialog("close");
        },
        "No": function() {
          $(this).dialog("close");
        }
      }
    });

  $("#orderform").on("submit", function(e) {
    $("#dialog-confirm").dialog("open");
    e.preventDefault();
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="dialog-confirm" title="Not so fast">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 
20px 0;"></span>Did you want to add a third for only $50? Click Yes to add</p>
</div>

<form id="orderform" action="/action_page.php">
  Package 1:<br>
  <input type="text" name="packageonename" value="">
  <br> Package 2:<br>
  <input type="text" name="packagetwoname" value="">
  <br><br>
  <input type="submit" value="Submit">
</form>

Upvotes: 2

Related Questions