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
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.
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.
You can use preventDefault method of the event object. Show activity on this post. Show activity on this post. stopPropagation should have no effect.
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.
<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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With