Form is still submitted even though listener function returns false
10,802
Solution 1
Looks like if you change your function to
var code = function(e) {
e.preventDefault();
}
It should do what you're looking for.
Solution 2
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.
<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>
Author by
Admin
Updated on July 23, 2022Comments
-
Admin almost 2 years
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.