john smith
john smith

Reputation: 733

form jquery prevent default

I want to prevent the form from submitting, but execute other form handlers, preventDefault stops all.

here's an example:

<form id="example">
    <input type="text" name="name" />
</form>

<form id="example2">
    <input type="text" name="name2" />
</form>

/* generic form handling */
$('form').submit(function(e) {
    alert('hello');
});

/* 
    specific example 
    i want this handler to prevent the form from submitting normally, but at the same time, i want it to execute the above code with the alert "hello"
*/
$('form#example').submit(function(e) {
    e.preventDefault(); // this stops the generic form handling (above) and standard form submission
});

Upvotes: 1

Views: 1015

Answers (2)

scrappedcola
scrappedcola

Reputation: 10572

Try returning false (http://api.jquery.com/submit/ states that returning false will stop from submitting):

$('form#example').submit(function(e) {
    return false;
});

Upvotes: 2

Dennis Hunink
Dennis Hunink

Reputation: 583

What happens if you replace

$('form#example').submit(function(e) {
    e.preventDefault(); // this stops the generic form handling (above) and standard form submission
});

by

$('#example').submit(function(e) {
    e.preventDefault(); // this stops the generic form handling (above) and standard form submission
});

Without testing, logics tells me that would make sense; you only prevent the actions on that specific form. Or am I mistaking your problem?

Upvotes: 1

Related Questions