gberg927 gberg927 - 16 days ago 12
HTML Question

Form Submit Execute Javascript Best Practice?

I would like to run a javascript function when a form is submitted. The issue right now is that everything is being appended to the URL as if it was using method=get. 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.

Answer

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>