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

发布于 2024-09-16 03:56:33 字数 835 浏览 8 评论 0原文

我在尝试取消表单提交时遇到了一些麻烦。我一直在关注本教程(即使我没有制作登录脚本),它似乎对他有用。

这是我的表单:

    <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?但我似乎无法让它发挥作用。我搜索了论坛,发现了一些有用的主题,但没有一个真正有效。我肯定搞砸了一些事情。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

自此以后,行同陌路 2024-09-23 03:56:33

尝试使用 event.preventDefault

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

Try using event.preventDefault

$(document).ready(function(event) {
    $('form[name=pForm]').submit(function(event){
        event.preventDefault();
        //add stuff here
    });
});
蓝颜夕 2024-09-23 03:56:33

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

onsubmit="return(false)

表格。这可行,但我仍然想知道一个可行的非内联 JavaScript 技巧。

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.

荒人说梦 2024-09-23 03:56:33

您指出“不显示‘return false’之前的警报”。

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

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.

策马西风 2024-09-23 03:56:33

它应该工作正常。可能还有更多问题。不幸的是,您问题中的代码不是 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

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.

凉城已无爱 2024-09-23 03:56:33

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

$('#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 (在我的例子中是匿名函数)。
所以......这是解决这个问题的一个原因的方法

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

ㄖ落Θ余辉 2024-09-23 03:56:33

只是我对这个(未回答,也过时)问题的微薄贡献。
我已经多次解决这个问题,总是使用相同的解决方案:

不要使用

<input name="submit" />

with

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

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

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.

夢归不見 2024-09-23 03:56:33

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

示例:

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

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;
});
雪落纷纷 2024-09-23 03:56:33

name 的值需要用引号引起来。试试这个:

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

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

$(document).ready(function() {
    $("form[name='pForm']").submit(function(){
        return false;
    });
});
如梦 2024-09-23 03:56:33

您必须执行某种“双重返回”,或者换句话说,您必须返回所返回的内容。所以,你有你的 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
}

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

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.

喵星人汪星人 2024-09-23 03:56:33

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

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 选择器。电子邮件必须是唯一的。

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.

呆头 2024-09-23 03:56:33

我也遇到了同样的问题,这取决于使用 Rails 和 :remote =>; true 在表单上。 Rails jQuery 驱动程序进入并通过 ajax 提交表单,而我自己的函数试图使用 return falseevent.preventDefault() 来阻止提交过程。

因此,请留意干扰您自己的 JavaScript 的框架和默认操作。 return false 应该可以:)

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

猫性小仙女 2024-09-23 03:56:33

这个怎么样?

$('form[name=pForm]').on('submit',function()
{
    console.log("(^o^)");
    return false;
});

How about this one?

$('form[name=pForm]').on('submit',function()
{
    console.log("(^o^)");
    return false;
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文