djreed
djreed

Reputation: 2733

Prevent Default on Form Submit jQuery

What's wrong with this?

HTML:

<form action="<URL>http://localhost:8888/bevbros/index.php/test"
          method="post" accept-charset="utf-8" id="cpa-form" class="forms">        
    <input type="text" name="zip" id="Zip" class="required valid">      
    <input type="submit" name="Next" value="Submit" class="forms" id="1">
</form>

jQuery:

$("#cpa-form").submit(function(e){
    e.preventDefault();
});

Upvotes: 180

Views: 603173

Answers (13)

bergee
bergee

Reputation: 121

Worked for me:

     $("#submitButtonOnForm").click(function(e) {            
        if (somecondition) {
            e.preventDefault();
            console.log('not submitted');
        }
        //form submission continues, no code needed
     });

Upvotes: 0

Hadayat Niazi
Hadayat Niazi

Reputation: 2480

Just define your button type and this will prevent the form to refresh the webpage

<button type="button" id="saveBtn">Save</button>
 $('#saveBtn').click(function() {

 });

Upvotes: 0

Chuck Le Butt
Chuck Le Butt

Reputation: 48826

This is an ancient question, but the accepted answer here doesn't really get to the root of the problem.

You can solve this two ways. First with jQuery:

$(document).ready( function() { // Wait until document is fully parsed
  $("#cpa-form").on('submit', function(e){

     e.preventDefault();

  });
})

Or without jQuery:

// Gets a reference to the form element
var form = document.getElementById('cpa-form');

// Adds a listener for the "submit" event.
form.addEventListener('submit', function(e) {

  e.preventDefault();

});

You don't need to use return false to solve this problem.

Upvotes: 26

Vigneshwar M
Vigneshwar M

Reputation: 113

Well I encountered a similar problem. The problem for me is that the JS file get loaded before the DOM render happens. So move your <script> to the end of <body> tag.

or use defer.

<script defer src="">

so rest assured e.preventDefault() should work.

Upvotes: 0

ndotie
ndotie

Reputation: 2160

e.preventDefault() works fine only if you dont have problem on your javascripts, check your javascripts if e.preventDefault() doesn't work chances are some other parts of your JS doesn't work also

Upvotes: 0

NFlows
NFlows

Reputation: 190

DEPRECATED - this part is outdated so please don't use it.

You can also try this code, if you have for example later added dynamic forms. For example you loaded a window async with ajax and want to submit this form.

$('#cpa-form').live('submit' ,function(e){
    e.preventDefault();      
    // do something
});

UPDATE - you should use the jQuery on() method an try to listen to the document DOM if you want to handle dynamically added content.

Case 1, static version: If you have only a few listeners and your form to handle is hardcoded, then you can listen directly on "document level". I wouldn't use the listeners on document level but I would try to go deeper in the doom tree because it could lead to performance issues (depends on the size of your website and your content)

$('form#formToHandle').on('submit'... 

OR

$('form#formToHandle').submit(function(e) {
    e.preventDefault();      
    // do something
});

Case 2, dynamic version: If you already listen to the document in your code, then this way would be good for you. This will also work for code that was added later via DOM or dynamic with AJAX.

$(document).on('submit','form#formToHandle',function(){
   // do something like e.preventDefault(); 
});

OR

$(document).ready(function() {
    console.log( "Ready, Document loaded!" );

    // all your other code listening to the document to load 

    $("#formToHandle").on("submit", function(){
        // do something           
    })
});

OR

$(function() { // <- this is shorthand version
   console.log( "Ready, Document loaded!" );

    // all your other code listening to the document to load 

    $("#formToHandle").on("submit", function(){
        // do something           
    })
});

Upvotes: 4

Jai Kathuria
Jai Kathuria

Reputation: 49

Your Code is Fine just you need to place it inside the ready function.

$(document).ready( function() {
  $("#cpa-form").submit(function(e){
     e.preventDefault();
  });
}

Upvotes: 3

shraddha Dharmamer
shraddha Dharmamer

Reputation: 157

$(document).ready(function(){
    $("#form_id").submit(function(){
        return condition;
    });
});

Upvotes: 3

Navi
Navi

Reputation: 19

Hello sought a solution to make an Ajax form work with Google Tag Manager (GTM), the return false prevented the completion and submit the activation of the event in real time on google analytics solution was to change the return false by e.preventDefault (); that worked correctly follows the code:

 $("#Contact-Form").submit(function(e) {
    e.preventDefault();
   ...
});

Upvotes: 1

towry
towry

Reputation: 4286

I believe that the above answers is all correct, but that doesn't point out why the submit method doesn't work.

Well, the submit method will not work if jQuery can't get the form element, and jQuery doesn't give any error about that. If your script is placed in the head of the document, make sure the code runs after DOM is ready. So, $(document).ready(function () { // your code here // }); will solve the problem.

The best practice is, always put your script in the bottom of the document.

Upvotes: 13

Crisalin Petrovschi
Crisalin Petrovschi

Reputation: 497

$('#cpa-form input[name="Next"]').on('click', function(e){
    e.preventDefault();
});

Upvotes: 7

scarver2
scarver2

Reputation: 7995

Use the new "on" event syntax.

$(document).ready(function() {
  $('form').on('submit', function(e){
    // validation code here
    if(!valid) {
      e.preventDefault();
    }
  });
});

Cite: https://api.jquery.com/on/

Upvotes: 76

Jordan Brown
Jordan Brown

Reputation: 13883

Try this:

$("#cpa-form").submit(function(e){
    return false;
});

Upvotes: 213

Related Questions