Reputation: 18831
I want to stop form from being submitted, and do something else instead (window.location.href
redirect to pretty-printed URL). But I cannot even get the basic part of preventing form from submitting.
As far as I understand it something like this should work:
$(function($){
$("#search_form").submit(function(e){
console.log("cancelling submit");
return false;
});
});
I also tried e.preventDefault()
, e.stopPropagation()
, and various combinations of these. "cancelling submit"
gets printed on Firebug console (so the event fires), but the form submits regardless, whatever I do.
jQuery documentation and logic imply that it should work, but it doesn't. Am I doing something wrong?
Hooking to click event might be easier but forms can be submitted in multiple ways - clicking buttons, pressing Enter, and probably something else I haven't thought about, so I'm trying to just take submit event.
I'm testing it all in Firefox.
EDIT: It turned out that <button type='submit' onclick='this.form.submit()'>Search</button>
was causing this. It seems silly in retrospect. Thanks to everyone for help.
Upvotes: 0
Views: 162
Reputation: 28711
I've just tested your code at: http://jsfiddle.net/UZwr5/
The code you've provided works in that demo. Most likely you have a error somewhere in your execution that prevents the return false;
from running.
Upvotes: 4
Reputation: 22319
try all of them together return false
and e.StopPropagation()
and e.preventDefault()
but more like this:
if(e.stopPropagation)
{
e.stopPropagation();
}
if(e.preventDefault)
{
e.preventDefault();
}
return false;
This keeps it much more cross browser compliant.
Upvotes: 1