[javascript] Prevent form redirect OR refresh on submit?

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.

This question is related to javascript jquery html forms

The answer is


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

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.


It looks like you're missing a return false.


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.


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

<form id="contactForm" action="#">

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"