jQuery对话框:确认单击提交按钮

9

我正在尝试使用jQuery创建一个确认对话框,但表单根本没有被提交,这是我得到的代码:

    <script type="text/javascript">
    var currentForm;
    $(function() {
        $("#dialog-confirm").dialog({
            resizable: false,
            height: 140,
            modal: true,
            autoOpen: false,
            buttons: {
                'Delete all items': function() {
                    currentForm.submit();
                    $(this).dialog('close');
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        });
    });

    function ask() {
        currentForm = $(this).closest('form');
        $("#dialog-confirm").dialog('open');
    }
</script>
<form ... >
    <input type="submit" value="delete" onclick="ask();return false;" />
</form>
4个回答

18

您需要让对话框按钮提交<form>,像这样:

               'Delete all items': function() {
                  $(this).dialog('close');
                  $("#myForm").submit();
                }

你的代码其余部分是正确的,但当前它只是关闭对话框并返回,你需要实际提交表单。此外,最好将其作为点击处理程序,而不是像这样使用 onclick,像这样(已更新评论):

    var currentForm;
    $(function() {
        $("#dialog-confirm").dialog({
            resizable: false,
            height: 140,
            modal: true,
            autoOpen: false,
            buttons: {
                'Delete all items': function() {
                    $(this).dialog('close');
                    currentForm.submit();
                },
                'Cancel': function() {
                    $(this).dialog('close');
                }
            }
        });
        $(".delete").click(function() {
          currentForm = $(this).closest('form');
          $("#dialog-confirm").dialog('open');
          return false;
        });
    });

那么只需要给你的 <input> 添加一个 class 属性,名称为 delete,就像这样:

<input class="delete" type="submit" value="delete" />

1
问题在于我有很多表单,每个表单里面都有一个删除按钮,它只是一个隐藏的输入 <input type="hidden" name='id' value='要删除的ID' />,这使得这些表单之间有所不同。 - Omu
1
@Omu - 当点击事件发生时,您可以在其中存储一个"currentForm = $(this).closest('form'),然后只需在删除按钮的处理程序中调用currentForm.submit(),无需使用ID...并且只需更改删除点击处理程序以使用类或属性选择器。 - Nick Craver
1
@Omu - 我的意思是针对答案的方法 :) 你现在的做法总体上不可行。我已经更新了答案,希望能够准确地表达我的意思。 - Nick Craver
1
Omu - 确保您在单击处理程序中像答案一样使用 return false - Nick Craver
2
@Omu - 哦,我的错,我甚至没有看到这个编辑,感谢您为未来的谷歌搜索者改进了它 :) - Nick Craver
显示剩余4条评论

5
如果您正在使用jQuery,则请正确地操作,避免内联JavaScript:
$(function (){
  $("form").submit(function (){
    // return false if you don't want this to be submitted
    // maybe do a
    // return ask();
    // but with the code provided it doesn't seem
    // to work like that - ask() is not returning anything at all!
  });
});

1
这对我有用:
 $(function () {
    $("#accordion").accordion({
        heightStyle: "content"
    });

    function confirmDialog(title, message, success) {
        var confirmdialog = $('<div></div>').appendTo('body')
            .html('<div><h6>' + message + '</h6></div>')
            .dialog({
                modal: true,
                title: title,
                zIndex: 10000,
                autoOpen: false,
                width: 'auto',
                resizable: false,
                buttons: {
                    Yes: function () {
                        success();
                        $(this).dialog("close");
                    },
                    No: function () {
                        $(this).dialog("close");
                    }
                },
                close: function () {
                    $(this).remove();
                }
            });

        return confirmdialog.dialog("open");
    }

    $('form').on('submit', function (e) {
        e.preventDefault();
        var form = this;

        confirmDialog('Confirm', 'Are you sure?', function () {
            form.submit();
        });
    });
});

参考:http://jsfiddle.net/pmw57/67Ge2/


1

对于一个使用 GET 方法的表单,我需要将按钮的值包含在查询字符串中,避免在表单提交时丢失它。

我使用了 event.preventDefault() 并在 JS 脚本中添加了按钮的名称和值作为隐藏的 <input> 字段。

JS 脚本:

$( function() {
  //Add function to all document's html tag with class="delete"
  $(document).on("click", ".delete", function(event) {

    event.preventDefault(); //Stop submitting form and wait for a "yes" or "no"

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

          //Prevent to lost button's value in query string at form submit
          //Need to add a hidden <input> field with the same button's name and value
          $('<input />').attr('type', 'hidden')
                        .attr('name', 'action')
                        .attr('value', 'delete')
                        .appendTo('#myform');

          $('#myform').submit(); //Ok proceed with form submit 

        },
        Cancel: function() {
          $( this ).dialog( "close" ); //Do nothing, close window.
        }
      }
    });
  });
});

表单模板
<div style="display:none" id="dialog-confirm" title="Empty the recycle bin?">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>

<form id="myform" action="#myurl" method="get">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input class="delete" type="submit" name="action" value="delete">
</form>

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Dialog - Modal confirmation</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
    $( function() {
      $(document).on("click", ".delete", function(event) {

        event.preventDefault(); //Stop submitting form and wait for a "yes" or "no"

        $( "#dialog-confirm" ).dialog({
          draggable: false,
          resizable: false,
          height: "auto",
          width: 400,
          modal: true,
          buttons: {
            "Delete items": function() {
              $( this ).dialog( "close" );
              
              //Prevent to lost button's value in query string at form submit
              //Need to add a hidden <input> field with the same button's name and value
              $('<input />').attr('type', 'hidden')
                            .attr('name', 'action')
                            .attr('value', 'delete')
                            .appendTo('#myform');

              $('#myform').submit(); //Ok proceed with form submit

            },
            Cancel: function() {
              $( this ).dialog( "close" ); //Do nothing, close window.
            }
          }
        });
      });
    });
  </script>
</head>
<body>
 
<div style="display:none" id="dialog-confirm" title="Empty the recycle bin?">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>

<form id="myform" action="#myurl" method="get">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input class="delete" type="submit" name="action" value="delete">
</form>
 
</body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接