2

I'm trying to use a jQuery UI Dialog for a sort of "soft" validation--if the form looks suspicious, warn the user, but allow them to continue the submission anyway:

// 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 
});

I've checked this out with a bunch of debugging alert statements. The control flow is exactly what I expect. If I first fail dataLooksFishy(), I am presented with the dialog and the method returns false asynchronously.

Clicking "yes" does re-trigger this method, and this time, the method returns true, however, the form does not actually submit...

I'm sure I'm missing a better methodology here, but the main target is to be able to simulate the behavior of the synchronous confirm() with the asynchronous dialog().

4

1 回答 1

0

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

  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;
    

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

于 2012-08-20T12:25:50.857 回答