Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent form from submitting via event.preventDefault(); not working

I'm using jQuery to submit my form variables, and im trying to prevent the form from submitting via the usual ways (click submit button or press enter on one of the fields)

i have this:

$('#form').submit(function(){
    event.preventDefault();
});

but it doesn't seem to work my form is still submitting, going to the process.php page..

like image 442
BrownChiLD Avatar asked Feb 24 '13 11:02

BrownChiLD


3 Answers

If the only thing you need to do is to prevent the default action, you can supply false instead of a function:

$('#form').submit(false);
like image 148
steveukx Avatar answered Nov 09 '22 09:11

steveukx


try return false instead of event.preventDefault() or accept event as a parameter of your function.

$('#form').submit(function(event){
  event.preventDefault();
});

Not sure why some people think this no longer works but here is an example showing it does still work.

https://jsfiddle.net/138z5atq/

Comment out the event handler and it will alert.

Regarding stopPropagation() and stopImmediatePropagation() they don't prevent the form from submitting at all. They just prevent the event from bubbling up the dom.

like image 8
Rob Avatar answered Nov 09 '22 11:11

Rob


Other way is:

$('#form').submit(function(){

   //some code here

   return false;
});
like image 7
dr.dimitru Avatar answered Nov 09 '22 09:11

dr.dimitru