Stop submitting form using submit eventener

I am trying to stop form submission using the event eventener function. My anonymous function executes, but the form still submits, even if false is returned at the end of the function. No JS errors occur.

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> 
+4
source share
3 answers

I always call event.preventDefault() for event listeners for which I want to cancel the event and also return false . It always works for me.

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

To prevent the form from submitting, I always used the onclick event to call the javascript method, which will do something, and then submit from there. You can also customize the form as follows:

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

After submitting, the validateForm () method can prevent the submission if necessary:

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

Ok, so 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 state that supports form validation status. It is better to update the status every time a field changes than to check only when the user tries to submit the entire form.

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

0
source

All Articles