jQuery - 取消表单提交(使用“return false”?)?

9

我在尝试取消表单提交时遇到了一些麻烦。我一直在按照这篇教程的步骤操作(尽管我没有制作登录脚本),他的方法似乎对他有效。

这是我的表单:

    <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>

下面是jQuery代码:

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

        return false;

    });
});

我已经在头部导入了jQuery,并且知道它正在工作。我的第一个想法是它可能已经过时,但实际上只有一年的时间。
那么,有人看到问题在哪里吗?
提前感谢。
编辑:根据我所读的,中止提交最简单和最适当的方法是返回false?但我似乎无法让它工作。我已经搜索了论坛并找到了几个有用的线程,但它们都没有真正起作用。我一定搞砸了什么。

1
是否发生了任何JavaScript错误? - Nick Craver
你的代码看起来完全正常,我建议在“return false;”之前加上alert,以查看是否实际到达了该部分。 - Nikita Rybak
没有错误。弹出窗口没有显示。:( - Nike
1
请尝试使用 alert($('form[name=pForm]').length); 而不是 _$(...).submit(..._,它将显示您的 jQuery 选择器是否找到任何内容。(返回的数字是找到的元素数量,因此0表示没有找到任何内容) - Nikita Rybak
12个回答

13

尝试使用event.preventDefault

$(document).ready(function(event) {
    $('form[name=pForm]').submit(function(event){
        event.preventDefault();
        //add stuff here
    });
});

10

谢谢大家的回复!我的一个朋友建议我添加

onsubmit="return(false)

在表单上是可行的,但我仍然想知道一个不使用内联JavaScript的技巧。


4

您提到“在'return false'之前的警报没有显示”。

使用jQuery时,提交元素的id或名称不能为“submit”-如果是,则不会触发提交事件。


3
没问题。请参见https://dev59.com/snA75IYBdhLWcg3wxcDV。 - Barmar

3
它应该能正常工作。可能还有其他问题。不幸的是,你提供的代码不符合SSCCE标准,因此很难确定根本原因。可能你根本没有导入jQuery库。或者在导入jQuery库之前调用了$(document).ready()。或者你有另一个JS库与$()冲突。或者实际表单没有所需的名称。等等。
为了让你开始,这里有一个完整的SSCCE。你只需要复制粘贴并运行它。
<!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>

如果它能正常工作(至少在这里是可以的,我会收到一个警报并且表单根本没有被提交),请将其与您自己的代码进行比较,并尝试将您自己的代码缩减为此格式,以便您可以更好地发现区别(从而找出错误)。
无论如何,在我看来,值得花费一些时间通过一些基本/琐碎的jQuery(最好也是JavaScript)教程,以便您更好地了解内部情况并学习如何使用像Firebug这样的工具。

2

我也遇到了这个问题,我的代码(不起作用的)大概是这样的:

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

在“before_submit”函数内,我使用了“return false”来阻止表单提交:

function before_submit() {

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

我在将事件处理程序函数绑定到表单时加入了"return",它起作用了:

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

附加到提交事件的函数必须返回false(在我的情况下是匿名函数)。 所以...这是解决此问题的一种方法


2

name的值需要加上引号。尝试这样做:

$(document).ready(function() {
    $("form[name='pForm']").submit(function(){
        return false;
    });
});

2
只有在需要转义时才需要引号 :) 在这种情况下,这不应该是一个问题。 - Nick Craver

2

您想访问的表单可能是动态添加到页面中的。在这种情况下,您需要使用委托来访问该表单。

示例:

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

2

这是我对这个(没有回答,而且日期也过时了)问题的一点小贡献。 我已经遇到了这个问题多次,但总是采用同样的解决方案:

不要使用

<input name="submit" />

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

这会触发错误的元素/项目,但不会出现任何错误或警告。因此,只需将提交按钮命名为其他名称,一切就会神奇地重新开始工作。

1
你需要进行一种“双重返回”的排序,换句话说,你必须返回被返回的内容。因此,你有了你的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>

那么你只需要一个名为onsubmit的jQuery函数,就像上面所示:

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

您可以在上面的函数中放置任何类型的条件语句。但是看起来您只是想取消它。希望这能对其他遇到此答案的人有所帮助。


0

我遇到过类似的问题。在验证之前,我通过删除表单的动作和方法来解决它们,然后在验证后再将它们添加回去。这是我编写的验证器:

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;
    };
};

你可以像这样实现:

$(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();
                });
});

您可以为所需字段添加CSS选择器。 邮箱字段的选择器必须是唯一的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接