Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery and jsFiddle, cannot get PreventDefault() to work on $.submit()

I've been trying to get this basic function to work for the last 2 hours, about 1/2 an hour of which was on jsFiddle. I don't know why, but I cannot get preventDefault() to work on a form submit button.

Here's the HTML:

<form action="" method="post">
    <input type="text" name="search-query" value="" id="search-query">
    <input type="submit" value="Search" name="submit" id="search-submit">
</form>​

and here's the JS:

$('#search-submit').submit(function(e) {
    e.preventDefault();
    alert("hello");
});​

When I try it in my own code, the form gets submitted as if the preventDefault() wasn't there.When I try it in jsFiddle, I get this error message:

{"error": "Shell form does not validate{'html_initial_name':
u'initial-js_lib', 'form': <mooshell.forms.ShellForm object
at 0x9139fcc>, 'html_name': 'js_lib', 'label': u'Js lib', 'field':
<django.forms.models.ModelChoiceField object at 0x91392cc>,
'help_text': '', 'name': 'js_lib'}"}

(I have no idea why the error is referencing mooTools, since I have jQuery 1.7.1 selected.) Here is the jsFiddle: http://jsfiddle.net/pv2TX/11/

Is there something wrong with my code? The selector I'm using should work, and I was able to call other jQuery events on it, but I can't seem to bind any kind of click handlers to it.

like image 950
Tim Mackey Avatar asked Feb 18 '26 22:02

Tim Mackey


1 Answers

submit is triggered on the form itself, not on the button that was clicked. From the docs:

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements.

So you just need to select your form instead of the button:

$("#form_selector").submit(function (e) {
    e.preventDefault();
});

Updated fiddle: http://jsfiddle.net/AvCCb/

like image 126
Andrew Whitaker Avatar answered Feb 21 '26 10:02

Andrew Whitaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!