【问题标题】:How to re-trigger a form submit event in jQuery UI dialog callback如何在 jQuery UI 对话框回调中重新触发表单提交事件
【发布时间】:2011-06-19 15:14:01
【问题描述】:

我正在尝试使用 jQuery UI 对话框进行某种“软”验证——如果表单看起来可疑,警告用户,但允许他们继续提交:

// multiple submit buttons...
var whichButton;
$("#myForm").find("[type=submit]").click(function()
{
  whichButton = this;
}

var userOkWithIt = false;
$("#myForm").submit(function()
{
  if (dataLooksFishy() && !userOkWithIt)
  {
    $("Are you sure you want to do this?").dialog(
    {
      buttons:
      {
        "Yes": function()
        {
          $(this).dialog("close");

          // override check and resubmit form
          userOkWithIt = true;
          // save submit action on form
          $("#myForm").append("<input type='hidden' name='" +
            $(whichSubmit).attr("name") + "' value='" +
            $(whichSubmit).val() + "'>");
          $("#myForm").submit(); /******  Problem *********/
        },
        "No": function() { $(this).dialog("close"); }
      }
    });
    return false; // always prevent form submission here
  } // end data looks fishy

  return true; // allow form submission 
});

我已经用一堆调试警报语句检查了这一点。控制流正是我所期望的。如果我第一次失败 dataLooksFishy(),我会看到对话框并且该方法异步返回 false。

点击“yes”确实会重新触发这个方法,而这一次,该方法返回true,然而,表单实际上并没有提交......

我确定我在这里错过了更好的方法,但主要目标是能够使用异步 dialog() 模拟同步 confirm() 的行为。

【问题讨论】:

  • 哎呀..打字错误:“whichButton”和“whichSubmit”变量名称应该彼此一致。那部分运行良好......

标签: jquery-ui dialog validation confirm


【解决方案1】:

如果我正确理解了您的问题 - 这就是解决方案。 (我已将操作分成单独的功能(更易于管理)):

  1. 提交表单(通常)会检查是否有错误 - dataLooksFishy()
  2. 如果有错误 - 应该会弹出一个对话框
  3. 如果用户点击“是” - 表单将使用“force=true”提交

    var
    form = $("#myForm"),
    
    formSubmit = function(force){
        if (dataLooksFishy() && force !== true) return showWarning();   // show warning and prevent submit
        else return true;                                               // allow submit
    },
    
    showWarning = function(){
        $("Are you sure you want to do this?").dialog({ buttons: {
            "Yes": function(){ $(this).dialog("close"); formSubmit(true); },
            "No": function() { $(this).dialog("close"); }
        }});
        return false;
    },
    dataLooksFishy = function(){ 
        return true;     // true when there are validation errors
    };
    
    // plain JS form submitting (also works if you hit enter in a text field in a form)
    form[0].onsubmit = formSubmit;
    

我无法使用您的表单对其进行测试,因为您没有在此处发布它。 如果您对此解决方案有疑问,请在此处发布更多代码,我会尽力提供帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    相关资源
    最近更新 更多