Form is still submitted even though listener function returns false

我怕爱的太早我们不能终老 提交于 2019-12-08 17:39:57

问题


I'm trying to figure out why this JavaScript doesn't stop the form from being submitted:

<form action="http://www.example.com" id="form">
    <input type="text" />
    <input type="submit" />
</form>

<script>
var code = function () {
    return false;
};
var element = window.document.getElementById("form");
if (element.addEventListener) {
    element.addEventListener("submit", code, false);
}
</script>

Unless I add the following onsubmit attribute to the form element:

<form action="http://www.example.com" id="form" onsubmit="return false">
    <input type="text" />
    <input type="submit" />
</form>

<script>
var code = function () {
    return false;
};
var element = window.document.getElementById("form");
if (element.addEventListener) {
    element.addEventListener("submit", code, false);
}
</script>

Seems like the addEventListener method alone should do the trick. Any thoughts? I'm on a Mac and I'm experiencing the same result on Safari, Firefox and Opera. Thanks.


回答1:


Combined the information from the two very helpful answers into a solution that works on both Mac and PC:

<script>
var code = function (eventObject) {
    if (eventObject.preventDefault) {
        eventObject.preventDefault();
    } else if (window.event) /* for ie */ {
        window.event.returnValue = false;
    }
    return true;
};
var element = window.document.getElementById("form");
if (element.addEventListener) {
    element.addEventListener("submit", code, false);
} else if (element.attachEvent) {
    element.attachEvent("onsubmit", code);
}
</script>



回答2:


Looks like if you change your function to

var code = function(e) {
    e.preventDefault();
}

It should do what you're looking for.

source




回答3:


I think what you're looking for is the preventDefault() method of the Event interface for browsers that implement it. It will cancel the form submission in the way you expected "return false" to.

More here and here.

<script type="text/javascript">
 var code = function (evt) {
            if (evt.preventDefault) {
                evt.preventDefault();
            }
            return false;
};
window.onload = function() {
    var element = window.document.getElementById("form");
    if (element.addEventListener) {
        element.addEventListener("submit", code, false);
    }
};
</script>


来源:https://stackoverflow.com/questions/967483/form-is-still-submitted-even-though-listener-function-returns-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!