在表单提交上触发jquery模式弹出窗口

时间:2018-03-12 02:46:14

标签: javascript jquery jquery-ui

这是我第一次使用jquery模式。我只是在提交表单时尝试显示弹出窗口。但相反,它会在页面加载时显示。我该如何解决?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>  

2 个答案:

答案 0 :(得分:2)

为了防止对话框自动打开,您可以在初始化对话框时将autoOpen属性设置为false

然后,在表单的提交事件中,您可以通过调用element.dialog("open")打开对话框。

请注意,我在提交事件处理程序中添加了event.preventDefault(),以防止表单提交。

&#13;
&#13;
$(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();
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以这样做

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

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