224

How do I prevent a form from submitting using jquery?

I tried everything - see 3 different options I tried below, but it all won't work:

    $(document).ready(function() { 

            //option A
            $("#form").submit(function(e){
                e.preventDefault();
            });

            //option B
            $("#form").submit(function(e){
                stopEvent(e);
            });

            //option C
            $("#form").submit(function(){
                return false;
            });
    });

What could be wrong?

Update - here is my html:

    <form id="form" class="form" action="page2.php" method="post"> 
       <!-- tags in the form -->
       <p class="class2">
           <input type="submit" value="Okay!" /> 
       </p>
    </form>

Is there anything wrong here?

Lucy Weatherford
  • 5,452
  • 16
  • 50
  • 76
  • Show your HTML because there is nothing wrong with preventDefault or return false as you posted it, other than your selector being totally wrong. – Sparky Feb 19 '12 at 06:53
  • 1
    `return false;` after the `.submit()` worked for me! I was having the same issue – d-_-b Sep 30 '12 at 21:05
  • If there is a JavaScript error occuring in the handler the `e.preventDefault();` code is not reached / executed. – Tom Dec 02 '19 at 21:43

15 Answers15

323

Two things stand out:

  • It possible that your form name is not form. Rather refer to the tag by dropping the #.
  • Also the e.preventDefault is the correct JQuery syntax, e.g.

        //option A
        $("form").submit(function(e){
            e.preventDefault();
        });
    

Option C should also work. I am not familiar with option B

A complete example:

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

        <script type='text/javascript'>
         $(document).ready(function() {
            //option A
            $("form").submit(function(e){
                alert('submit intercepted');
                e.preventDefault(e);
            });
        });
        </script>
    </head>

    <body>
        <form action="http://google.com" method="GET">
          Search <input type='text' name='q' />
          <input type='submit'/>
        </form>
    </body>
</html>
Arijit Mukherjee
  • 3,817
  • 2
  • 31
  • 51
Philip Fourie
  • 111,587
  • 10
  • 63
  • 83
  • 3
    Something else is wrong. I am using this technique on a daily basis. Best guess would be that there are JavaScript errors on the page, perhaps check it with FireBug? – Philip Fourie Feb 19 '12 at 06:58
  • @LucyWeatherford, I have updated my answer with a sample that works. Maybe you spot someting. – Philip Fourie Feb 19 '12 at 07:23
  • In your update html I noticed that you have class attribute for your form. Change your JQuery selector from `$('#form')` to `$('.form')` for class attributes. – Philip Fourie Feb 19 '12 at 07:30
  • nice catch, but i had an id as well, i just deleted it meanwhile and changed the selector to ("form") as you suggested. Anyhow I tried now (".form") and it didn't work either... – Lucy Weatherford Feb 19 '12 at 07:58
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/7906/discussion-between-philip-fourie-and-lucy-weatherford) – Philip Fourie Feb 19 '12 at 08:02
  • 1
    thanks! I ended up using your code on the same page, and it worked, still unsure what was wrong though, but it's all good now. thanks! – Lucy Weatherford Feb 19 '12 at 08:16
  • 2 things that may have solved this: 1. I moved the js to the same page (maybe something was getting in the way). 2. I deleted various other js I had on the page which may have been getting in the way as well. Now it works. yay! – Lucy Weatherford Feb 19 '12 at 08:31
  • Here it is working for me using e: function(e) and e.preventDefault(e); how does "e" work´s it stands for exception? – Ângelo Rigo Jun 20 '16 at 14:28
  • 1
    @ÂngeloRigo e is simply the name you give to the parameter, in this case it's the submit event. – squall3d Jul 01 '16 at 15:53
  • thing is its working for restriction, but it don't when i want to submit the from – Habib Rehman Jun 14 '17 at 15:57
  • I have tried with your solution, but form is still being submitted. – Kamlesh Sep 07 '19 at 07:21
43

You probably have few forms o the page and using $('form').submit() adds this event to the first occurrence of the form on your page. Use class selector instead, or try this:

$('form').each(function(){
    $(this).submit(function(e){
        e.preventDefault();
        alert('it is working!');
        return  false;
    })
}) 

or better version of it:

$(document).on("submit", "form", function(e){
    e.preventDefault();
    alert('it works!');
    return  false;
});
Lewis James-Odwin
  • 1,019
  • 7
  • 6
Artem Kiselev
  • 643
  • 1
  • 7
  • 7
26

To prevent default/prevent form submission use

e.preventDefault();

To stop event bubbling use

e.stopPropagation();

To prevent form submission 'return false' should work too.

Jens
  • 8,423
  • 9
  • 58
  • 78
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • See this answer because jQuery handles these differently. http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false – Sparky Feb 19 '12 at 06:51
  • 1
    Check this to understand event bubling http://www.quirksmode.org/js/events_order.html – The Alpha Feb 19 '12 at 06:54
  • 3
    The [jQuery on](http://api.jquery.com/on/) API states: "Returning false from an event handler will automatically call `event.stopPropagation()` and `event.preventDefault()`. A `false` value can also be passed for the handler as a shorthand for `function(){ return false; }`." – Paul Aug 21 '15 at 19:05
9

I also had the same problem. I also had tried what you had tried. Then I change my method not to use jquery but by using "onsubmit" attribute in the form tag.

<form onsubmit="thefunction(); return false;"> 

It works.

But, when I tried to put the false return value only in thefunction(), it doesn't prevent the submitting process, so I must put return false; on onsubmit attribute.

Luki B. Subekti
  • 822
  • 10
  • 9
  • 1
    It is the difference between `false;` and `return false;`. You'd need to have `onsubmit="return thefunction();"` – xr280xr Jun 30 '20 at 22:30
6

I had the same problem and I solved this way (not elegant but it works):

$('#form').attr('onsubmit','return false;');

And it has the advantage, in my opinion, that you can revert the situation any time you want:

$('#form').attr('onsubmit','return true;');
vinxxe
  • 61
  • 1
  • 1
  • 1
    Maybe it would be a little more comfortable to just remove the attribute when reverting the form submit prevention `$('#form').removeAttr('onsubmit');` – barbieswimcrew Jun 01 '17 at 05:27
5

Attach the event to the submit element not to the form element. For example in your html do like this

$('input[type=submit]').on('click', function(e) {
    e.preventDefault();
});
M Weiss
  • 51
  • 1
  • 1
2

You may simply check if the form is valid if yes run submit logic otherwise show error.

HTML

<form id="form" class="form" action="page2.php" method="post">
    <input type="text" class="check-validity" value="" />
    <input type="text" class="check-validity" value="" />
    <input type="text" class="check-validity" value="" />
    <input type="text" class="check-validity" value="" />
    <input type="text" class="check-validity" value="" />
    <input type="text" class="check-validity" value="" />
    <input type="text" class="check-validity" value="" />

    <input type="submit" value="Okay!" />
</form>

Javascript

    $(document).ready(function () {
        var isFormValid = true;

        function checkFormValidity(form){
            isFormValid = true;
            $(form).find(".check-validity").each(function(){
                var fieldVal = $.trim($(this).val());
                if(!fieldVal){
                    isFormValid = false;
                }
            });
        }


        //option A
        $("#form").submit(function (e) {
            checkFormValidity("#form");
            if(isFormValid){
                alert("Submit Form Submitted!!! :D");
            }else{
                alert("Form is not valid :(");
            }
            e.preventDefault();
        });
    });
Code Spy
  • 9,626
  • 4
  • 66
  • 46
2

Using jQuery, you can do the following:

  1. Use the native form submit event with a Submit button, while preventing the event from firing, then

  2. Check the form Valid property.

This can be implemented as following:

  1. HTML:

    <form id="yourForm">
         <input id="submit" type="submit" value="Save"/>
    </form>
    
  2. JavaScript:

    $("form").on("submit", function (e) {
         e.preventDefault();
         if ($(this).valid()) {  
              alert('Success!');
         }
    });
    
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Mohamed Nagieb
  • 819
  • 9
  • 11
1

You forget the form id, and it works

$('form#form').submit(function(e){
   e.preventDefault();
   alert('prevent submit');             
});
1

When I am using <form> tag without the attribute id="form" and call it by its tag name directly in jquery it works with me.
your code in html file :

<form action="page2.php" method="post">

and in Jquery script:

$(document).ready(function() {
      $('form').submit(function(evt){
          evt.preventDefault();// to stop form submitting
      });
 });
Noha Salah
  • 493
  • 1
  • 7
  • 11
1

This also appears to work and may be slightly simpler:

$('#Form').on('submit',function(){
    return false;
})
Ukuser32
  • 2,147
  • 2
  • 22
  • 32
1

The information is missing how to prevent the form submit and then revert the situation, i. e. allow the form submit later on.

Here is an example:

var savebtn_clicked;

$('form#commentform').submit( function(e) {
    return savebtn_clicked;
});

$('#savebtn').click( function() {
    savebtn_clicked = true;
    $('#form#commentform').submit();
});

In my case every button fired the form. With the code above I could control which button allowed the form to be submitted.

Avatar
  • 14,622
  • 9
  • 119
  • 198
1

Prevent submitting form data and then release.

  $("form").on("submit", function (e) {
   e.preventDefault();
   alert('Ok');
   $( this ).unbind( 'submit' ).submit(); // Release 
  });
  • It's working
Subroto Biswas
  • 553
  • 7
  • 5
1

$('#form') looks for an element with id="form".

$('form') looks for the form element

Jens
  • 8,423
  • 9
  • 58
  • 78
Rahul
  • 1,866
  • 17
  • 32
0
// Prevent form submission
$( "form" ).submit(function( event ) {
  event.preventDefault();
});

from here: https://api.jquery.com/submit-selector/ (interesting page on submit types)