I would like to run a JavaScript function when a form is submitted. The issue is that, when the form is submitted, the page is reloaded and the form values are appended to the URL as GET parameters. I would like it to stay on the current page and only run the JavaScript function.
I was wondering what the best practice (or what you do) to avoid having the page reload and parameters be sent.
Use the
onsubmitevent to execute JavaScript code when the form is submitted. You can then return false or call the passed event’spreventDefaultmethod to disable the form submission.For example:
This works, but it’s best not to litter your HTML with JavaScript, just as you shouldn’t write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so: