繁体   English   中英

JavaScript阻止表单提交

[英]JavaScript Prevent Form Submit

我试图让我的表单在我按下JavaScript对话框上的“取消”按钮时不提交。

我有以下代码:

  $(document).ready(function() {
    $("#submit").click(function (e) {
        e.preventDefault();
        var link = $(this).attr("href"); // "get" the intended link in a var
        var result = confirm("Are you sure you want to log this fault?");
        if (result) {
            document.location.href = link;  // if result, "set" the document location      
        }
    });
});

即使我具有“阻止”默认代码,无论我按“确定”还是“取消”按钮,都将提交表单。

我的HTML代码是:

<button type="submit" id="submit" class="btn btn-default"><span class="glyphicon glyphicon-floppy-save"></span></button>
<form id="myform" method="post" action="/the/post/url">

<!-- other elements -->
....
....
....

<button type="submit" id="submit" class="btn btn-default">
    <span class="glyphicon glyphicon-floppy-save"></span>
</button>

</form>

$(function() {
    //this would do the same as button click as both submit the form
    $(document).on("submit", "#myform", function (e) {
        var result = confirm("Are you sure you want to log this fault?");
        //if cancel is cliked
        if (!result) {
             return false;      
        }
        //if ok is cliked, form will be submitted
    });
});

下面的类似操作将不起作用,因为this与没有href属性的Submit按钮有关。

var link = $(this).attr("href"); // is invalid.

尝试

 $(document).ready(function() {
    $("#submit").click(function (e) {
        e.preventDefault();
        var result = confirm("Are you sure you want to log this fault?");
        if (result) {
        $('#formId').submit(); // where formId is the id of your form
          document.location.href = "url to which you want to redirect";      
        }
        else
        return false;
       });
});

旁注:无论您从哪里获得这段代码,它们都必须使用样式像按钮的超链接<a> ,并带有有效的href属性:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM