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();
});
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
djreed
  • 2,673
  • 4
  • 22
  • 21
  • 13
    Works fine [here](http://jsfiddle.net/Town/YtpQY/). 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 '11 at 00:47
  • 3
    That link is internal and of no use to us. – Steve Robbins Jun 24 '11 at 00:52
  • Perhaps an older version was cached. Looks to be working now. – djreed Jun 24 '11 at 08:10
  • 1
    possible duplicate of [event.preventDefault() vs. return false](http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) – Liam Aug 21 '14 at 12:58
  • 2
    ! Make sure the javascript code runs after DOM is ready. – towry Apr 25 '15 at 15:10

13 Answers13

206

Try this:

$("#cpa-form").submit(function(e){
    return false;
});
Jordan Brown
  • 13,603
  • 6
  • 30
  • 29
  • 16
    It works, but why doesn't the preferred method of preventDefault work? – MikeJ Mar 18 '13 at 19:03
  • 26
    See this question for a better explanation: http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false – Jordan Brown Mar 18 '13 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. – Chuck Le Butt Jun 11 '18 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/

scarver2
  • 7,887
  • 2
  • 53
  • 61
  • 3
    Hi. This doesn't work for me. (yes, I put my code inside `$(document).ready()`) How do I make it work? – Gui Imamura Jul 24 '15 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 '15 at 16:28
  • Hello, I'm using `$('#myFormID').validationEngine('validate')` from [jQuery validationEngine](https://github.com/posabsolute/jQuery-Validation-Engine) 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? – Gui Imamura Jul 27 '15 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 '15 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.

Mike Cole
  • 14,474
  • 28
  • 114
  • 194
Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
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.

towry
  • 4,131
  • 1
  • 18
  • 25
7
$('#cpa-form input[name="Next"]').on('click', function(e){
    e.preventDefault();
});
Adrian Wragg
  • 7,311
  • 3
  • 26
  • 50
  • This works perfect for me on a page where I have a client side form inside a server side form. – Liknes Jan 26 '18 at 09:39
3
$(document).ready(function(){
    $("#form_id").submit(function(){
        return condition;
    });
});
joelhed
  • 60
  • 6
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           
    })
});
NFlows
  • 180
  • 1
  • 11
  • 7
    `.live()` is deprecated since jQuery 1.7 and removed since 1.9. Use `.on()` instead. – Hank May 12 '15 at 10:06
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
    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. – mickmackusa Mar 27 '17 at 01:24
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();
   ...
});
Navi
  • 19
  • 5
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

ndotie
  • 1,830
  • 17
  • 18
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.

Vigneshwar M
  • 83
  • 1
  • 10
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() {

 });
Hadayat Niazi
  • 1,991
  • 3
  • 16
  • 28
0

Worked for me:

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