Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept a form submit in JavaScript and prevent normal submission

There seems to be lots of info on how to submit a form using javascript, but I am looking for a solution to capture when a form has been submitted and intercept it in javascript.

HTML

<form>  <input type="text" name="in" value="some data" />  <button type="submit">Go</button> </form> 

When a user presses the submit button, I do not want the form to be submitted, but instead I would like a JavaScript function to be called.

function captureForm() {  // do some stuff with the values in the form  // stop form from being submitted } 

A quick hack would be to add an onclick function to the button but I do not like this solution... there are many ways to submit a form... e.g. pressing return while on an input, which this does not account for.

Ty

like image 935
mrwooster Avatar asked Mar 21 '11 22:03

mrwooster


People also ask

How does JavaScript prevent a form from being submitted?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.

How do I restrict a form from submission?

The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.

How do you stop form from resetting on submit?

You can use preventDefault method of the event object. Show activity on this post. Show activity on this post. stopPropagation should have no effect.

How do I keep form data after submitting the form using JavaScript?

To keep the values, you must fill in the values on the server while rendering the page. Usually, you can simply copy the data from the HTML request parameters into the fields. Usually, you cannot simply copy the HTML request parameters into the fields.


1 Answers

<form id="my-form">     <input type="text" name="in" value="some data" />     <button type="submit">Go</button> </form> 

In JS:

function processForm(e) {     if (e.preventDefault) e.preventDefault();      /* do what you want with the form */      // You must return false to prevent the default form behavior     return false; }  var form = document.getElementById('my-form'); if (form.attachEvent) {     form.attachEvent("submit", processForm); } else {     form.addEventListener("submit", processForm); } 

Edit: in my opinion, this approach is better than setting the onSubmit attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.

Edit2: Updated my example to include preventDefault()

like image 59
Michael McTiernan Avatar answered Oct 03 '22 11:10

Michael McTiernan