174

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();
});
5
  • 13
    Works fine here. Can you post more information in your question? If you alert() in the submit handler does it get called? If not, then it could be that there's an error in your script that's prevent the event handler from being wired up correctly. Anything in the error console?
    – Town
    Jun 24, 2011 at 0:47
  • 3
    That link is internal and of no use to us. Jun 24, 2011 at 0:52
  • Perhaps an older version was cached. Looks to be working now.
    – djreed
    Jun 24, 2011 at 8:10
  • 1
    possible duplicate of event.preventDefault() vs. return false
    – Liam
    Aug 21, 2014 at 12:58
  • 2
    ! Make sure the javascript code runs after DOM is ready.
    – towry
    Apr 25, 2015 at 15:10

13 Answers 13

206

Try this:

$("#cpa-form").submit(function(e){
    return false;
});
3
  • 16
    It works, but why doesn't the preferred method of preventDefault work?
    – MikeJ
    Mar 18, 2013 at 19:03
  • 26
    See this question for a better explanation: stackoverflow.com/questions/1357118/… Mar 18, 2013 at 19:15
  • 10
    This is the wrong answer. e.preventDefault() works fine with a form submission, the problem lay elsewhere in the OP's code. Using return false could result in unintended consequences. Jun 11, 2018 at 17:44
70

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/

4
  • 3
    Hi. This doesn't work for me. (yes, I put my code inside $(document).ready()) How do I make it work? Jul 24, 2015 at 20:21
  • 1
    @GuiImamura Need more info. Did you set the valid variable to true or false? Can you recreate your code in jsfiddle.net and send the link? Try adding an alert() to confirm that the function is firing. Some people have reported that adding e.stopPropagation(); after e.preventDefault(); stops other chained events from firing.
    – scarver2
    Jul 25, 2015 at 16:28
  • Hello, I'm using $('#myFormID').validationEngine('validate') from jQuery validationEngine as variable valid, to check wether the input is a valid e-mail address. Nevertheless, I want it to prevent the default behaviour either way; does preventDefault have to be inside the if block, not before it? Jul 27, 2015 at 20:00
  • @GuiImamura Glad to hear you got it to work. The preventDefault is inside the if not valid block to stop the submission of the form. In other words, if valid, use the form's default behavior.
    – scarver2
    Jul 27, 2015 at 22:41
25

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.

1
  • I replaced native js event listener instead of jquery event listener and it's work. thank you for idea.
    – Orhan Gazi
    Dec 24, 2019 at 20:19
13

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.

7
$('#cpa-form input[name="Next"]').on('click', function(e){
    e.preventDefault();
});
1
  • This works perfect for me on a page where I have a client side form inside a server side form.
    – Liknes
    Jan 26, 2018 at 9:39
3
$(document).ready(function(){
    $("#form_id").submit(function(){
        return condition;
    });
});
0
3

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

$(document).ready( function() {
  $("#cpa-form").submit(function(e){
     e.preventDefault();
  });
}
1
  • 1
    This advice is already provided by other answers. Please remove this answer to reduce page bloat. You can upvote the other answer(s) that represent the same sentiment. Mar 27, 2017 at 1:24
3

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           
    })
});
1
  • 7
    .live() is deprecated since jQuery 1.7 and removed since 1.9. Use .on() instead.
    – Hank
    May 12, 2015 at 10:06
1

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

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

0

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.

0

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() {

 });
0

Worked for me:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.