本文介绍了JavaScript阻止表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我按下JavaScript对话框上的取消"按钮时,我试图不提交表单.

I'm trying to get my form to not submit when I press the cancel button on my JavaScript dialog.

我有此代码:

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

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

The form submits regardless if I press the Ok or Cancel buttons or not even though I have the prevent default code.

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

这篇关于JavaScript阻止表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:59
查看更多