DerFuchs10
DerFuchs10

Reputation: 137

Submit a form with jquery doesn't work

I have a form:

<form action="thanks.php" onsubmit="return false" class="submitForm">
... Some Inputs ...
</form>

and a jQuery Code:

$(document).ready(function() {
       $("form.submitForm").on("submit", function() {
        $("form.submitForm").attr("onsubmit", "return true");
        $("form.submitForm").submit;
    });
});

Now I like to submit the form with the jQuery Code. It works, BUT only at the second enter or submit... I don't understand why it doesn't work...

Thanks for any help!

Sorry for my english mistakes, I'm from Germany.

Upvotes: 2

Views: 5173

Answers (1)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

Why it doesn't submit :

Your form doesnt submit because you have the onsubmit attribute to return false. That is preventing the form from submiting, which is probably what you want since you try to resubmit it with $("form.submitForm").submit;. Unfortunnatly, this will not work since you need to add brackets like that : $("form.submitForm").submit();

Why it submit the second time :

On the first submit, you are preventing the default behavior (return false), but you are changing the onsubmit attribute to return true. That will remove the default prevention you had at first.

So overall, you clikc the first time, prevent default behavior with return false, doesnt submit because there is a misstake in $("form.submitForm").submit; and then change the return false to true, removing what was preventing the form from submitting.

Solution :

Use this code :

$(document).ready(function() {
    $("form.submitForm").on("submit", function(e) {
        e.preventDefault()
        $("form.submitForm").submit();
    });
});

But if you have nothing else in that code, why brother preventdefault and then do the default behavior?

Upvotes: 2

Related Questions