The form is still submitted even if the listener function returns false

I am trying to understand why this JavaScript does not stop form submission:

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

It looks like the addEventListener method should do the trick. Any thoughts? I am on a Mac and I experience the same result in Safari, Firefox and Opera. Thanks.

+7
javascript forms onsubmit addeventlistener
source share
3 answers

Combine the information from two very useful 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> 
+8
source share

It looks like if you change your function to

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

He must do what you seek.

a source

+6
source share

I think you are looking for the preventDefault() method of the Event interface for browsers that implement it. It will cancel the form submission as you expected " return false ".

More details 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> 
+2
source share

All Articles