停止表单提交的一种方法是从JavaScript函数返回false。

当单击提交按钮时,将调用验证函数。我有一个表单验证的案例。如果满足这个条件,我调用一个名为returnToPreviousPage()的函数;

function returnToPreviousPage() {
    window.history.back();
}

我正在使用JavaScript和Dojo工具包。

它不是返回到前一页,而是提交表单。我如何终止这次提交并返回到上一页?


当前回答

禁用提交按钮也可以帮助阻止表单提交。

<input style="display:none" type="submit" disabled>

其他回答

只需使用一个简单的按钮,而不是提交按钮。并调用JavaScript函数来处理表单提交:

<input type="button" name="submit" value="submit" onclick="submit_form();"/>

函数:

function submit_form() {
    if (conditions) {
        document.forms['myform'].submit();
    }
    else {
        returnToPreviousPage();
    }
}

你也可以尝试window.history.forward(-1);

以下是目前为止的工作(在Chrome和Firefox中测试):

<form onsubmit="event.preventDefault(); validateMyForm();">

其中validateMyForm()是一个函数,如果验证失败则返回false。关键是使用名称事件。我们不能使用例如e.c preventdefault()。

禁用提交按钮也可以帮助阻止表单提交。

<input style="display:none" type="submit" disabled>

Hemant和Vikram的回答在Chrome浏览器中并不完全适用。event.preventDefault ();脚本阻止页面提交,无论是否通过验证。相反,我必须移动event.preventDefault();输入if语句,如下所示:

    if(check if your conditions are not satisfying) 
    { 
    event.preventDefault();
    alert("validation failed false");
    returnToPreviousPage();
    return false;
    }
    alert("validations passed");
    return true;
    }

感谢赫曼特和维克拉姆让我走上正轨。

假设你有一个类似的形式

<form action="membersDeleteAllData.html" method="post">
    <button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>

下面是confirmAction函数的javascript

<script type="text/javascript">
    function confirmAction(e)
    {
        var confirmation = confirm("Are you sure about this ?") ;

        if (!confirmation)
        {
            e.preventDefault() ;
            returnToPreviousPage();
        }

        return confirmation ;
    }
</script>

这一个工作在Firefox, Chrome, Internet Explorer(edge), Safari等。

如果不是这样,请告诉我