Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Cancel form submit (using "return false"?)?

I'm running into a bit of trouble while trying to cancel the submit of a form. I've been following this tutorial (even though i'm not making a login script), and it seems to be working for him.

Here's my form:

    <form action="index.php" method="post" name="pForm">
        <textarea name="comment" onclick="if(this.value == 'skriv här...') this.value='';" onblur="if(this.value.length == 0) this.value='skriv här...';">skriv här...</textarea>
        <input class="submit" type="submit" value="Publicera!" name="submit" />
    </form>

And here's the jquery:

$(document).ready(function() {
    $('form[name=pForm]').submit(function(){

        return false;

    });
});

I've already imported jQuery in the header and i know it's working. My first thought was that it might be outdated, but it's actually "just" a year ago.

So do anyone see what's wrong?

Thanks in advance.

EDIT: From what i've read the easiest and most appropriate way to abort the submit is to return false? But i can't seem to get it working. I've searched the forum and i've found several helpful threads but none of them actually works. I must be screwing something up.

like image 791
Nike Avatar asked Aug 25 '10 18:08

Nike


People also ask

How do I stop a form from submitting in jQuery?

We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.

What happens when Onsubmit returns false?

It means that do nothing on submit.

How do you stopping form submit if the validation fails?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.

How do I stop submitting a form?

The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.


2 Answers

Try using event.preventDefault

$(document).ready(function(event) {
    $('form[name=pForm]').submit(function(event){
        event.preventDefault();
        //add stuff here
    });
});
like image 195
Adam Avatar answered Oct 13 '22 15:10

Adam


The value of name needs quotes around it. Try this:

$(document).ready(function() {
    $("form[name='pForm']").submit(function(){
        return false;
    });
});
like image 32
Brian Ray Avatar answered Oct 13 '22 16:10

Brian Ray