未显示确认对话框

Confirmation Dialog is not showing

本文关键字:对话框 确认 显示      更新时间:2023-09-26

我以前从未在jquery中工作过。这是我第一次。我需要它进行一些确认对话框。在申请我的项目之前,我已经写了这个来测试它。我已经编写了这段代码。仅当选择了指定的单选按钮时,我才需要对话框。

主要问题:如果选择了单选按钮中的指定选项,则显示确认对话框。

Jquery代码:

(function($){
    $.fn.checkLeave = function() {
        return this.each(function(){
            if($("input[name='second']").is(':checked')) {
                alert("Second Radio Button is CLicked");
                $.confirm({
                    text: "Are you sure to submit the form",
                        title: "Confirmation required",
                        confirm: function(button) {
                          $("form").submit();
                        },
                        cancel: function(button) {
                        // nothing to do
                        },
                        confirmButton: "Yes",
                        cancelButton: "No",
                        post: true,
                        confirmButtonClass: "btn-default",
                        cancelButtonClass: "btn-danger",
                        dialogClass: "modal-dialog modal-lg" 
                });     
            }
            });
    };
})( jQuery );

HTML是:

 <form action="dialogJquery.html" method="post">
    <input type="text" name="username" placeholder="Username">
    <input type="radio" id="first">
    <input type="radio" name="second" checked="">
    <input type="submit" value="Submit" id="submit" name="confirm"
      onclick="$(this).checkLeave();"></button>
 </form>

上面的代码显示了在对话框之前定义的警报。 但之后不会显示对话框。这是我使用 Jquery 对话框插件的地方。但是通过调试,当调试器达到 $.confirm 并且我单击单步跳过然后显示对话框时,但当我恢复脚本时,它再次消失。

基本问题是表单正在提交,因为您的代码没有执行任何操作来阻止它被提交。 因此,对话框仅在浏览器提交表单并转到指定页面 (dialogJquery.html) 所需的时间内显示。

一旦一个更好的程序员看到这一点,他们可能会想出一个更好的解决方案,但以下是我想出的似乎有效的解决方案。 我已经在元素中添加了一些 ID 等 - 您应该能够遵循它而无需进一步解释。 我发现的一件事是,如果任何元素的名称或ID为"submit",那么.submit()函数将无法在表单上工作。

通常,我处理表单的提交事件并防止默认,以便它不提交。 确认按钮将提交确认设置为 true 并提交表单。

.HTML

  <form id="myForm" action="dialogJquery.html" method="post">
    <input type="text" name="username" placeholder="Username">
    <input type="radio" id="first">
    <input type="radio" name="second" checked>
    <input type="submit" value="Submit" id="btnSubmit" name="confirm">
  </form>

爪哇语

(function($) {
  var submitConfirm = false;
  $("#myForm").submit(function(event) {
    if (!submitConfirm) {
      event.preventDefault();
      if ($("input[name='second']").is(':checked')) {
        $.confirm({
          text: "Are you sure to submit the form",
          title: "Confirmation required",
          confirm: function(button) {
            submitConfirm = true;
            $("#myForm").submit();
          },
          cancel: function(button) {
            // nothing to do
          },
          confirmButton: "Yes",
          cancelButton: "No",
          post: true,
          confirmButtonClass: "btn-default",
          cancelButtonClass: "btn-danger",
          dialogClass: "modal-dialog modal-lg"
        });
      }
    }
  });
})(jQuery);