James Dawson
James Dawson

Reputation: 5409

jQuery not preventing form from being submitted

I want to prevent a form from being submitted using jQuery and instead run a function when the user wants to submit.

Here's my forms markup:

<form action="" method="post" id="msg-form">
    <p><textarea name="msg"></textarea><input type="submit" value="Send"></p>
</form>

And my Javascript code:

$('#msg-form').submit(function() {
    return false;
}

However, when I press the submit button, the form still gets sent and the page refreshes. How can I properly prevent the form from submitting?

Upvotes: 2

Views: 2081

Answers (6)

Tadeck
Tadeck

Reputation: 137320

It seems the event handler is not even executed, thus I assume the form could not have been found. Try enclosing your code within handler executed when the DOM is ready. In jQuery it can be simply done like that:

$(function(){
    $('#msg-form').submit(function(event) {
        event.preventDefault();
        // code executed when user tries to submit the form
    });
});

Also, as you can see above, you can prevent default behaviour of the form when it is being submitted.

Upvotes: 1

Travis J
Travis J

Reputation: 82277

This works

<form action='' onsubmit="return false;">

As does this

<form action='' onsubmit="doSomeWork();return false;">

Upvotes: 0

Jamund Ferguson
Jamund Ferguson

Reputation: 17014

The submit event is not actually being bound to the form element. You may have forgotten to bind it after the DOM was loaded!

Put the event binding inside of $(document).ready(function() { or load the script at the bottom of the page (after all of the elements have loaded).

Upvotes: 1

Jesse Atkinson
Jesse Atkinson

Reputation: 11406

Try:

$("#msg-form").submit(function (e) {
    e.preventDefault();
});

Upvotes: 0

Ansel Santosa
Ansel Santosa

Reputation: 8444

You could not give the users a real submit button and only submit the form using JS after validation:

HTML

<form action="" method="post" id="msg-form">
    <p><textarea name="msg"></textarea><input id="submit" type="button" value="Send"></p>
</form>

JS

$('#submit').on('click', function() {
    // validate
    $('#msg-form')[0].submit();
});

Upvotes: 0

j08691
j08691

Reputation: 207901

$('#msg-form').submit(function(e){ e.preventDefault(); });

Upvotes: 0

Related Questions