如何有条件地提交表格?

300*_*300 1 html javascript forms jquery

我在动态 html 页面中使用以下表单和提交按钮。

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

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

我想做的是,当用户提供特定输入时,然后显示一个警告框,询问用户是否想要提交更改或只是停留在同一页面而不提交更改。

我可以显示警报框(在 stackoverflow 成员的帮助下),但与 window.alert 一起我应该添加到 JavaScript 中,这样如果用户在 window.confirm 上单击“取消”,则不会提交表单;如果用户单击“”,则不会提交表单确定”窗口上确认?

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();
});
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 5

您只需要更改逻辑,以便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()
    }
});
Run Code Online (Sandbox Code Playgroud)

小提琴示例

如果您单击“确定”,您将看到表单已提交(并且 jsFiddle 发出使用 POST 请求的警告 - 但这是正常的),而单击“取消”则不会执行任何操作。