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

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

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

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

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


当前回答

使用防止默认

Dojo Toolkit

dojo.connect(form, "onsubmit", function(evt) {
    evt.preventDefault();
    window.history.back();
});

jQuery

$('#form').submit(function (evt) {
    evt.preventDefault();
    window.history.back();
});

香草JavaScript

if (element.addEventListener) {
    element.addEventListener("submit", function(evt) {
        evt.preventDefault();
        window.history.back();
    }, true);
}
else {
    element.attachEvent('onsubmit', function(evt){
        evt.preventDefault();
        window.history.back();
    });
}

其他回答

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

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

例如,如果你在表单上有提交按钮,为了阻止它的传播,只需编写event.preventDefault();在点击提交按钮或进入按钮时调用的函数中。

我建议不要使用onsubmit,而是在脚本中附加一个事件。

var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
  submit.addEventListener("click", returnToPreviousPage);
} else {
  submit.attachEvent("onclick", returnToPreviousPage);
}

然后使用preventDefault()(或returnValue = false对于旧浏览器)。

function returnToPreviousPage (e) {
  e = e || window.event;
  // validation code

  // if invalid
  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }
}

假设你有一个类似的形式

<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等。

如果不是这样,请告诉我

基于@Vikram Pudi的回答,我们也可以用纯Javascript做到这一点

<form onsubmit="submitForm(event)">
    <input type="text">
    <input type="submit">
</form>

<script type="text/javascript">

    function submitForm(event){
        event.preventDefault();


    }
</script>