JavaScript阻止表单提交

时间:2014-03-16 13:07:56

标签: javascript jquery forms

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

由于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;
       });
});

旁注:从你获得这段代码的地方开始,他们必须使用带有有效href属性的超链接<a>样式:)