Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  46] [ 7]  / answers: 1 / hits: 148014  / 13 Years ago, thu, november 10, 2011, 12:00:00

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.


More From » html

 Answers
63

Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault method to disable the form submission.



For example:



<script>
function doSomething() {
alert('Form submitted!');
return false;
}
</script>

<form onsubmit=return doSomething(); class=my-form>
<input type=submit value=Submit>
</form>


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:



<script>
$('.my-form').on('submit', function () {
alert('Form submitted!');
return false;
});
</script>

<form class=my-form>
<input type=submit value=Submit>
</form>

[#89202] Wednesday, November 9, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
haden

Total Points: 638
Total Questions: 95
Total Answers: 99

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
;