Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event.preventDefault() not working in Firefox (JSFiddle included)

This is a kind of similar duplicate to some others here, but I think I'm using event.preventDefault() correctly in this case.

Here's a JSFiddle you can see the code with: http://jsfiddle.net/SeEw2/2/

Basically, click the Submit button.

In Chrome: Nothing happens - correct response.

In Firefox: Page reloads, oh noes!

So why is the page reloading in Firefox and not Chrome? I've been Firebugging it and no errors come up in either...

like image 841
Jack Avatar asked Jan 03 '11 15:01

Jack


People also ask

What does preventDefault () method do in jQuery?

The event.preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form.

What is the event preventDefault?

Definition and Usage The event.preventDefault () method stops the default action of an element from happening.

Why is preventDefault not working in FF?

There was some funky shit going on with your anonymous functions not being closed correctly too which is why it displayed the behaviour which made you think preventDefault was not working in FF.

What is the default action of the event is not triggered?

Description: If this method is called, the default action of the event will not be triggered. This method does not accept any arguments. For example, clicked anchors will not take the browser to a new URL.


2 Answers

The variable event in your code is not initialized.

http://jsfiddle.net/SeEw2/4/

extract :

 $('#ajaxsearch').click(function(event) {          // Stop the Search input reloading the page by preventing its default action         event.preventDefault(); 
like image 77
Shikiryu Avatar answered Sep 19 '22 08:09

Shikiryu


Ah I've had a similar problem in that past. Rather than event.preventDefault() try passing the event to:

    function ie8SafePreventEvent(e){     if(e.preventDefault){ e.preventDefault()}     else{e.stop()};      e.returnValue = false;     e.stopPropagation();         } 

I know it says IE, but I've never had a problem with it since =]

like image 27
Dartoxian Avatar answered Sep 21 '22 08:09

Dartoxian