JavaScript防止表单提交

JavaScript Prevent Form Submit

本文关键字:表单提交 JavaScript      更新时间:2023-09-26

当我按下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      
        }
    });
});

无论我是否按下Ok或Cancel按钮,表单都会提交,即使我有防止默认代码。

我的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
    });
});

下面的like将不起作用,因为this指向没有href属性的提交按钮。

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属性:)