Using JQuery - preventing form from submitting

Lucy Weatherford picture Lucy Weatherford · Feb 19, 2012 · Viewed 376.4k times · Source

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?

Answer

Philip Fourie picture Philip Fourie · Feb 19, 2012

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>