Prevent form redirect OR refresh on submit?
Asked Answered
P

7

112

I've searched through a bunch of pages, but can't find my problem, so I had to make a post.

I have a form that has a submit button, and when submitted I want it to NOT refresh OR redirect. I just want jQuery to perform a function.

Here's the form:

<form id="contactForm">
    <fieldset>
        <label for="Name">Name</label>
        <input id="contactName" type="text" />
    </fieldset>

    <fieldset>
        <label for="Email">Email</label>
        <input id="contactEmail" type="text" />
    </fieldset>

    <fieldset class="noHeight">
        <textarea id="contactMessage" cols="20"></textarea>
        <input id="contactSend" class="submit" type="submit" onclick="sendContactForm()" />
    </fieldset>
</form>        
<small id="messageSent">Your message has been sent.</small>

And here is the jQuery:

function sendContactForm(){
    $("#messageSent").slideDown("slow");
    setTimeout('$("#messageSent").slideUp();$("#contactForm").slideUp("slow")', 2000);
}

I've tried with and without an action element on the form, but don't know what I'm doing wrong. What has annoyed me more is that I have an example that does it perfectly: Example Page

If you want to see my problem live, goto stormink.net (my site) and check out the sidebar where it says "Send me and email" and "RSS Subscription". Both are forms that I'm trying to get this to work on.

Paginal answered 12/8, 2009 at 1:50 Comment(0)
P
195

Just handle the form submission on the submit event, and return false:

$('#contactForm').submit(function () {
 sendContactForm();
 return false;
});

You don't need any more the onclick event on the submit button:

<input class="submit" type="submit" value="Send" />
Purge answered 12/8, 2009 at 1:53 Comment(6)
I remember the moment that I learned one could return false from a from a submit to not submit was also the moment that I started to really like the Javascript/DOM system.Piling
Amazing. Where can I find specification docs explaining that false prevents submission?Gogh
you should really use e.preventDefault() instead of just returning false..Shooin
@Juan Not the case if you're using JQuery.Loupgarou
@RogerFilmyer wrong. if you use "return false;" you are also stopping propagation, which will cause UX issues. For example, if you are expecting a "click" to bubble up or something like that.Shooin
exactly what i was looking for. i was trying to apply this to the button element, not the form. wonder why it works on the form but not hte buttonSurfactant
H
21

Here:

function submitClick(e)
{
     e.preventDefault();
     $("#messageSent").slideDown("slow");
     setTimeout('$("#messageSent").slideUp();
     $("#contactForm").slideUp("slow")', 2000);
}

$(document).ready(function() {
    $('#contactSend').click(submitClick);
});

Instead of using the onClick event, you'll use bind an 'click' event handler using jQuery to the submit button (or whatever button), which will take submitClick as a callback. We pass the event to the callback to call preventDefault, which is what will prevent the click from submitting the form.

Holp answered 12/8, 2009 at 1:57 Comment(3)
$('#contactSend').click(submitClick(e)); It says to me that 'e' is not defined.. :/Olathe
Should be $('#contactSend').click(function(e) { submitClick(e) }); or $('#contactSend').click(submitClick);Wiltshire
What about a vanilla JS solution?Evelinaeveline
U
10

In the opening tag of your form, set an action attribute like so:

<form id="contactForm" action="#">
Usually answered 23/6, 2015 at 3:46 Comment(3)
+1 for simple solution. But unfortunately the page will still refresh the first time the user hits enter. A bad work around would be to call myForm.submit(); as soon as possible, but then you're loading the page twice.Vintner
it won't refresh the first time.Audiometer
This answer needs to be voted down, because it DOES NOT solve the original question, and makes the situation worse by actually changing the url after the page reloads. You need to either e.preventDefault() or in return false in the onsubmit function. #19454810Sparry
S
9

It looks like you're missing a return false.

Stereoisomer answered 12/8, 2009 at 1:53 Comment(0)
W
7

If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):

<input name="o" required="required" aria-required="true" type="text">

You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:

$('form').on('submit', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment

As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.

So if you want to get rid of these default pop-ups, use the click event on the submit button:

$('form input[type=submit]').on('click', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes
Wilone answered 30/5, 2018 at 16:18 Comment(0)
J
2

An alternative solution would be to not use form tag and handle click event on submit button through jquery. This way there wont be any page refresh but at the same time there is a downside that "enter" button for submission wont work and also on mobiles you wont get a go button( a style in some mobiles). So stick to use of form tag and use the accepted answer.

Jewish answered 3/9, 2014 at 17:37 Comment(0)
L
1

Unlike most of the previous answers, the solution that is described here demonstrates how to prevent a page from refreshing/redirecting on <form> submission using pure Javascript, instead of JQuery.

The HTML form

Below is the HTML <form>. There is no need to use the onclick event (which fires when the user uses the mouse to click on a button) or the onsubmit event (which fires when the user hits the enter key) on the submit button. These events are taken care of by the JS code described in the following section.

<form id="myForm">
   <input type="text" name="contactName" id="contactName">
   <input class="submit" type="submit" value="Submit">
</form>

The JavaScript code

Below is the JavaScript code to handle the <form> submission on the submit event. The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

Note: Make sure to register the event handler after the HTML element is added to the DOM tree (when loading the webpage); otherwise, a runtime error will be caused, as you'll be trying to set a property (an event handler) of a non-existent object. One way to ensure this is to simply place the script after the element in question (i.e., <form>), but as this might be a bit dangerous—since you are relying on how you assume a browser works—you can assign the event handler after the initial HTML document has been completely loaded and parsed, using the DOMContentLoaded event. Example:

document.addEventListener('DOMContentLoaded', (event) => {
    document.getElementById("myForm").addEventListener("submit", function(e) {
        e.preventDefault() // Cancel the default action
        sendContactForm();
    });
});

Putting it all together

<!DOCTYPE html>
<html>
   <head>
      <script>
         document.addEventListener('DOMContentLoaded', (event) => {
             document.getElementById("myForm").addEventListener("submit", function(e) {
                 e.preventDefault() // Cancel the default action
                 sendContactForm();
             });
         });
      </script>
   </head>
   <body>
      <form id="myForm">
         <input type="text" name="contactName" id="contactName">
         <input class="submit" type="submit" value="Submit">
      </form>
   </body>
</html>
Lalittah answered 15/8, 2022 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.