javascript 使用提交事件侦听器停止表单提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5915893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:46:34  来源:igfitidea点击:

Stop form submission with submit eventlistener

javascripthtmljavascript-events

提问by Ian McIntyre Silber

I'm trying to stop a form from submitting using the submit eventlistener. My anonymous function runs but the form still submits, even with return false at the end of the function. There are no JS errors being thrown.

我试图阻止使用提交事件侦听器提交表单。我的匿名函数运行但表单仍然提交,即使在函数结束时返回 false。没有抛出 JS 错误。

Am I making some stupid mistake?

我犯了一些愚蠢的错误吗?

<form id="highlight">
    Row: <input type="text" name="rows" value="1" id="rows">
    Column: <input type="text" name="cells" value="1" id="cells">
    <input type="submit" name="Submit" value="Highlight" id="Submit">
</form>

<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function() {
        alert('hi');
    return false;
}, false);
</script>

回答by Jim Rubenstein

I always call event.preventDefault()on event listeners that I want to cancel the event for, as well as return false. This always works for me.

我总是调用event.preventDefault()我想取消事件的事件侦听器,以及 return false。这总是对我有用。

<script>
var highlight_form = document.getElementById('highlight');

highlight_form.addEventListener('submit', function(event)
{
    event.preventDefault();
    alert('hi');
    return false;

}, false);
</script>

回答by Kyle

To prevent form submission, I've always used the "onclick" event to call a javascript method which will do something and then submit from there. You can also setup the form as follows:

为了防止表单提交,我一直使用“onclick”事件来调用一个 javascript 方法,该方法将执行某些操作然后从那里提交。您还可以按如下方式设置表单:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Once submitted, the validateForm() method can prevent submission if necessary:

一旦提交,validateForm() 方法可以在必要时阻止提交:

function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}

回答by kuroi neko

Well this is the way I would do it :

那么这就是我会做的方式:

function validate (form)
{
    // return false if some fields are not right
}

function setup_form_validation (form)
{
    form.addEventListener (
        'submit',
        function (f) { // closure to pass the form to event handler
            return function (evt) {
                if (!validate (f)) evt.preventDefault();
                // Return status doesn't work consistently across browsers,
                // and since the default submit event will not be called in case
                // of validation failure, what we return does not matter anyway.
                // Better return true or nothing in case you want to chain other
                // handlers to the submit event (why you would want do that is
                // another question)
            };
        } (form),
    false);
}

I would rather have a boolean holding the form validation status, though. Better update the status each time a field changes than do the check only when the user tries to submit the whole form.

不过,我宁愿有一个布尔值来保存表单验证状态。每次字段更改时更新状态比仅在用户尝试提交整个表单时进行检查更好。

And of course this will fail in IE8- and other older browsers. You would need yet another bloody event abstraction layer to make it work everywhere.

当然,这将在 IE8- 和其他旧浏览器中失败。您将需要另一个该死的事件抽象层,以使其在任何地方都能正常工作。