jQuery - 取消表单提交(使用“返回假”?)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3569072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Cancel form submit (using "return false"?)?
提问by Nike
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:
这是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.
我已经在标题中导入了 jQuery,我知道它正在工作。我的第一个想法是它可能已经过时了,但它实际上“只是”一年前。
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.
编辑:从我读过的内容来看,中止提交的最简单和最合适的方法是返回 false?但我似乎无法让它工作。我搜索了论坛,发现了几个有用的主题,但没有一个真正有效。我一定是搞砸了什么。
回答by Adam
Try using event.preventDefault
$(document).ready(function(event) {
$('form[name=pForm]').submit(function(event){
event.preventDefault();
//add stuff here
});
});
回答by Nike
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.
在表格上。这有效,但我仍然想知道一个有效的非内联javascript技巧。
回答by user1129673
You indicate that "that the alert before the 'return false' doesn't show".
您指出“未显示 'return false' 之前的警报”。
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.
使用 jQuery 时,提交元素的 id 或名称不能是 'submit' - 如果是,则不会触发提交事件。
回答by nobug
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.
这会触发错误的元素/项目,不会带来错误或警告。因此,只需将您的提交按钮命名为其他名称,一切都会神奇地重新开始工作。
回答by BalusC
It should work fine. There's likely more at matter. Unfortunately the code in your question is not in an SSCCEflavor 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()
beforeimporting jQuery library. Or you have another JS library which is conflicting $()
. Or the actual form doesn't have the desired name. Etc..etc..
它应该可以正常工作。可能还有更多问题。不幸的是,您问题中的代码不是SSCCE风格,因此很难确定根本原因。可能您根本没有导入 jQuery 库。或者您$(document).ready()
在导入 jQuery 库之前调用。或者你有另一个冲突的 JS 库$()
。或者实际表单没有所需的名称。等等等等。
To get you started, here's a fullworthy SSCCE. All you need to do is to copy'n'paste'n'run it.
为了让您开始,这里有一个完全值得的 SSCCE。您需要做的就是复制'n'paste'n'run它。
<!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.
无论如何,在我看来,学习一些基本/琐碎的 jQuery(最好还有 JavaScript)教程是值得的,这样您就可以更好地了解幕后发生的事情并学习如何使用Firebug 之类的工具。
回答by bogdan
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:
在“before_submit”函数中,我有“return false”来阻止表单提交:
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
附加到提交事件的函数必须返回 false(在我的例子中是匿名函数)。所以......这是这个问题的一个原因的一种解决方案
回答by Sai Teja Reddy
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;
});
回答by Brian Ray
The value of name needs quotes around it. Try this:
name 的值需要用引号括起来。尝试这个:
$(document).ready(function() {
$("form[name='pForm']").submit(function(){
return false;
});
});
回答by KeatsKelleher
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.
您可以为必填字段添加 CSS 选择器。电子邮件的一个必须是唯一的。
回答by John H
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()
.
我遇到了同样的问题,这:remote => true
取决于使用 Rails 和表单。Rails jQuery 驱动程序进来并通过 ajax 提交表单,而我自己的函数正在尝试使用return false
和来拖延提交过程event.preventDefault()
。
So look out for frameworks and default actions that interfere with your own javascript. return false
should work :)
因此,请注意干扰您自己的 javascript 的框架和默认操作。return false
应该管用 :)