60

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.

1
  • 1
    To avoid parameters be sent? :o Don't you mean, to avoid the parameter to show up in browser address bar? Basicaly using POST instead of GET would also solve this (useful to know if you'd like to support JS-disabled clients as well, such as several mobile phone users). Commented Nov 10, 2011 at 16:36

3 Answers 3

101

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>
Sign up to request clarification or add additional context in comments.

3 Comments

While browsers may be able to deal with it correctly I'd like to suggest closing the <input> tag for better consistency, e.g. <input type="submit" value="Submit" />
If you'd like to use vanilla Javascript (in my opinion you should always try to): document.getElementsByClassName('.my-form')[0].addEventListener('submit',function(){ alert('Form submitted'); return false; });
@moteutch and how would you pass the values of potential form input fields to the function? should it just find them in the document or can i somehow pass them as function parameters?
14

I know it's a little late for this. But I always thought that the best way to create event listeners is directly from JavaScript. Kind of like not applying inline CSS styles.

function validate(){
    //do stuff
}
function init(){
    document.getElementById('form').onsubmit = validate;
}
window.onload = init;

That way you don't have a bunch of event listeners throughout your HTML.

3 Comments

This is true, but I opted to go with the simplest option for this question.
This doesn't work for me. The whole function doesn't get executed before the form is submitted.
@Sahand could you provide example code next time? Martin's answer was very general
4

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.