9

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.

Nike
  • 1,189
  • 3
  • 8
  • 8

12 Answers12

12

Try using event.preventDefault

$(document).ready(function(event) {
    $('form[name=pForm]').submit(function(event){
        event.preventDefault();
        //add stuff here
    });
});
Adam
  • 39,529
  • 15
  • 101
  • 139
9

Thanks for the respond everybody! A friend of mine tipsed me to add

onsubmit="return(false)

on the form. That works, but i'd still like to know a not-inline-javascript trick that works.

Nike
  • 1,189
  • 3
  • 8
  • 8
4

You indicate that "that the alert before the 'return false' doesn't show".

When using jQuery, the id or name of the submit element can not be 'submit' - if it is, then the submit event won't be fired.

random_user_name
  • 23,924
  • 7
  • 69
  • 103
  • 3
    This is correct. See http://stackoverflow.com/questions/3117755/jquery-doesnt-submit-a-form – Barmar Sep 23 '12 at 00:39
2

Just my humble contribution to this (unanswered, dated too) question. I've run on this problem several times already always with the same solution:

Don't use

<input name="submit" />

along with

$('form').submit(function(){...});

This fires the wrong element/item bringing no errors nor warnings. So just name your submit button something else and everything magically starts working again.

nobug
  • 132
  • 7
2

The form you're trying to access might be dynamically added to your page. You need to use delegate to access that form in that case

Example:

    $(document).delegate("#myform","submit",function(){
       return false;
});
2

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

$(document).ready(function() {
    $("form[name='pForm']").submit(function(){
        return false;
    });
});
isherwood
  • 46,000
  • 15
  • 100
  • 132
Brian Ray
  • 1,453
  • 3
  • 22
  • 18
2

It should work fine. There's likely more at matter. Unfortunately the code in your question is not in an SSCCE flavor so that it's hard to nail down the root cause. Probably you didn't import jQuery library at all. Or you called $(document).ready() before importing jQuery library. Or you have another JS library which is conflicting $(). Or the actual form doesn't have the desired name. Etc..etc..

To get you started, here's a fullworthy SSCCE. All you need to do is to copy'n'paste'n'run it.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 3569072</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $('form[name=pForm]').submit(function() {
                    alert('Submit blocked!');
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <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>
    </body>
</html>

If it works (at least, it works here, I get an alert and the form isn't submitted at all), compare it with your own code and try to cutdown your own code into this flavor so that you can better spot the differences (and thus your mistake).

Regardless, in my opinion it will be worth the effort to get yourself through some basic/trivial jQuery (and preferably also JavaScript) tutorials so that you get a better understanding what's going on under the covers and learn how to use tools like Firebug.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
2

I also had this problem, my code (that didn't work) was something like this:

$('#upload_form').submit(function(){ before_submit('argument') });

and inside the "before_submit" function i had "return false" to stop the form from submitting:

function before_submit() {

.........................................................
return false;
}

I put "return" when binding the event handler function to the form and it worked:

$('#upload_form').submit(function(){ return before_submit('argument') });

The function attached to the submit event has to return false (in my case the anonymous function). So...this is one solution to one cause of this problem

bogdan
  • 1,179
  • 3
  • 11
  • 18
0

I had this same problem and it was down to using Rails and :remote => true on the form. Rails jQuery driver was coming in and submitting the form by ajax while my own function was trying to stall the submission process using return false and event.preventDefault().

So look out for frameworks and default actions that interfere with your own javascript. return false should work :)

John H
  • 2,418
  • 20
  • 34
0

You have to do a sort of 'double return', or in other words, you have to return what is returned. So, you have your html:

<form action="index.php" onsubmit="return cancelSubmit()" 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>

Than you just have a jquery function that is called onsubmit as you see above:

function cancelSubmit() {
    return false; // return true if you want submission to carry through
}

You can put any sort of conditionals in the function above. It seems you simply want to cancel it though. Hope this helps for others that come across this answer.

BestAnswer
  • 127
  • 16
0

I've run into similar issues. I solved them by removing the action and method of the form prior to validation and then adding them back in after validation. Here is the validator I wrote:

var Validator = function (formSelector) {
    this.formSelector = formSelector;
//  $(formSelector).submit(function() {return false;});
        this.Action = $(formSelector).attr("action");
        this.Method = $(formSelector).attr("method");
    $(formSelector).attr("action",function(){return ""}).attr("method",function(){return ""});  
        var donotsubmit = false;
        var notjustcheckbox = false;
        var checknotchecked = false;
    this.Required = new Array();
    this.Email = new Array();
    this.validate = function () {
        this.form = $(this.formSelector);
        var i = 0;
        for (i in this.Required){
            $(this.Required[i]).attr("value", function(index,attr){
                // Check on checkboxes...   
                if (this.getAttribute("type") == "checkbox"){
                    if (this.checked == false){ 
                        checknotchecked = true;
                        donotsubmit = true;
                    } else {
                    }       
                } else {    
                    if (attr == "" || attr == undefined){   
                        this.style.border = "1px solid red";
                        notjustcheckbox = true;
                        donotsubmit = true;     
                    } else {
                        this.style.border = "1px solid green";
                    }
                }
            });
        }
        i = 0;
        for (i in this.Email){
            $(this.Email[i]).attr("value", function(index,email){
                var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i ;
                if (filter.test(email) == true || filter.test(email) == "true") {
                    this.style.border = "1px solid green";
                } else if (filter.test(email) == false) {
                    donotsubmit = true;
                    notjustcheckbox = true;
                    this.style.border = "1px solid red";
                }
            });
        }
        if (donotsubmit == true){
            if (checknotchecked == true && notjustcheckbox == true){    
                alert("Please correct the fields in red and check the required checkboxes");
            } else if (checknotchecked == true && notjustcheckbox == false){
                alert("Please check the required checkboxes");
            } else {
                alert("Please correct the fields in red");
            }
            checknotchecked = false;
            notjustcheckbox = false;
            donotsubmit = false;
        } else {
            $(formSelector).attr({action : ''+this.Action+''});
            $(formSelector).attr({method : ''+this.Method+''});
            $(formSelector).submit();   
        }
        return true;
    };
};

You can implement it like this:

$(document).ready(function(){
    var myForm = new Validator("#formId");
        myForm.Required = new Array("input.lightborder");
                myForm.Email = new Array("#email");
                $("#form-submit-button-id").click(function(){
                    myForm.validate();
                });
});

You can add CSS Selectors for required fields. The one for Email must be unique.

KeatsKelleher
  • 9,063
  • 4
  • 41
  • 47
0

How about this one?

$('form[name=pForm]').on('submit',function()
{
    console.log("(^o^)");
    return false;
});
usayama_dx
  • 11
  • 2
  • Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Thanks – sɐunıɔןɐqɐp Jul 04 '18 at 08:55