Using JQuery - preventing form from submitting

JqueryForms

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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>

Solution 2 - Jquery

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;
});

Solution 3 - Jquery

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.

Solution 4 - Jquery

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.

Solution 5 - Jquery

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;');

Solution 6 - Jquery

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();
});

Solution 7 - Jquery

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();
        });
    });

Solution 8 - Jquery

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

$('form') looks for the form element

Solution 9 - Jquery

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
      });
 });

Solution 10 - Jquery

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!');
        }
    });

Solution 11 - Jquery

You forget the form id, and it works

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

Solution 12 - Jquery

// Prevent form submission
$( "form" ).submit(function( event ) {
  event.preventDefault();
});

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

Solution 13 - Jquery

This also appears to work and may be slightly simpler:

$('#Form').on('submit',function(){
	return false;
})

Solution 14 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLucy WeatherfordView Question on Stackoverflow
Solution 1 - JqueryPhilip FourieView Answer on Stackoverflow
Solution 2 - JqueryArtem KiselevView Answer on Stackoverflow
Solution 3 - JqueryThe AlphaView Answer on Stackoverflow
Solution 4 - JqueryLuki B. SubektiView Answer on Stackoverflow
Solution 5 - JqueryvinxxeView Answer on Stackoverflow
Solution 6 - JqueryM WeissView Answer on Stackoverflow
Solution 7 - JqueryCode SpyView Answer on Stackoverflow
Solution 8 - JqueryRahulView Answer on Stackoverflow
Solution 9 - JqueryNoha SalahView Answer on Stackoverflow
Solution 10 - JqueryMohamed NagiebView Answer on Stackoverflow
Solution 11 - JqueryShintadoniku AlyssaView Answer on Stackoverflow
Solution 12 - JqueryChris StrongView Answer on Stackoverflow
Solution 13 - JqueryUkuser32View Answer on Stackoverflow
Solution 14 - JqueryAvatarView Answer on Stackoverflow