2015-09-04 85 views
1

我正在使用以下表单并在我的动态html页面中提交按钮。如何有条件地提交表单?

<form method=\"post\" class=\"my-form\" >

<input type=\"submit\" name=\"submitButton\" value=\"Submit\" id=\"button1\" />

我所试图做的是当一个特定的输入由用户提供,则显示一个警告框,询问用户要提交更改或只是留在同一页面上而不提交更改。

我可以显示警报框(在stackoverflow成员的帮助下),但随着window.alert我应该添加到JavaScript,所以如果用户在window.confirm上点击“取消”并且表单被提交如果用户在window.confirm上点击“ok”

JavaScript的例子是在fiddle

$(document).on('input', '.my-input', function(){ 
    $(this).closest('form').addClass('changed'); 
}); 

$(document).on('submit', '.my-form', function(e){ 
    if($(this).hasClass('changed')){ 
    var x=window.confirm("You have set a unique threshold for one or more states below. Are you sure you want to reset them all?") 
    if (x) 
     window.alert("Thresholds changed!") 
    else 
     window.alert("Thresholds not changed!") 
    } 
    $(this).removeClass('changed'); 
    e.preventDefault(); 
}); 

回答

4

你只需要改变你的逻辑,这样当用户拒绝确认框preventDefault()只调用。试试这个:

$(document).on('submit', '.my-form', function (e) { 
    if ($(this).hasClass('changed')) { 
     var allowSubmit = window.confirm("You have set a unique threshold for one or more states below. Are you sure you want to reset them all?") 
     if (!allowSubmit) 
      e.preventDefault() 
    } 
}); 

Example fiddle

如果你点击“确定”,你会看到的形式提交(和的jsfiddle警告使用POST请求 - 但这是正常的),而点击'取消'什么也不做。

+0

谢谢罗里,它正常工作,因为我一直在寻找。有一个疑问:如果我输入一个值并单击提交按钮,我会看到带有“ok”和“cancel”按钮的警报窗口。如果我点击取消,那么页面将保持原样并且表单不会被提交(这是预期的)。但是,如果我再次点击提交,那么表单将直接提交,而不显示带有“ok”和“cancel”按钮的警报窗口。 我怎样才能确保警报窗口显示每次提交被点击(如果在文本框中的值改为) – 300

+0

那是因为你需要删除'removeClass()'行 - 我更新了我的回答对你 –

+0

再次感谢罗里。它现在工作很完美。 – 300

0

你也可以在提交函数处理程序中返回false,它应该可以工作。以this question为例。