jQuery preventDefault() 提交表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7194673/
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
preventDefault() submitting form
提问by Osman
Ok i am fairly new to jquery and javascript in general. I have a form, and what i want to do it have the form run a function to make sure everything is there, and all the variables are correct then submit. I have used onclick
value to the submit button and have it run a function that uses preventDefault()
. I am not sure if im using it correctly but it doesn't seem to be working. This is what i have and when you click submit, it just submits even if the if statement is false.
好的,我一般对 jquery 和 javascript 还是比较陌生。我有一个表单,我想做的是让表单运行一个函数来确保一切都在那里,并且所有的变量都是正确的,然后提交。我已经onclick
对提交按钮使用了value 并让它运行了一个使用preventDefault()
. 我不确定我是否正确使用它,但它似乎不起作用。这就是我所拥有的,当您单击提交时,即使 if 语句为假,它也会提交。
function checkSubmitStatus() {
$("#myform").submit(function(event){
if( whatever==true) {
event.preventDefault();
}
});
}
<input type="submit" name="submit" value="Submit" onClick="checkSubmitStatus()">
Thanks!
谢谢!
回答by Blazemonger
By putting $("#myform").submit(...)
inside the checkSubmitStatus()
function, you're attaching the submit handler after the button is clicked and the form is already submitted. Try this:
通过放入函数$("#myform").submit(...)
内部checkSubmitStatus()
,您将在单击按钮并且表单已经提交后附加提交处理程序。尝试这个:
<script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(function(event){
if(whatever) {
event.preventDefault();
}
});
});
</script>
<form id="myform">
<input type="submit" name="submit" value="Submit">
</form>
回答by genesis
Change
改变
<input type="submit" name="submit" value="Submit" onClick="checkSubmitStatus()">
to
到
<input type="submit" name="submit" value="Submit" >
and change your javascript to
并将您的 javascript 更改为
$("#myform").submit(function(event){
if( whatever==true)
{
event.preventDefault();
}
});
回答by PeeHaa
You can just drop the checkSubmitStatus()
function.
您可以删除该checkSubmitStatus()
功能。
$("#myform").submit(function(event){
if(whatever == true) {
event.preventDefault();
}
});
Also drop this:
也放下这个:
onClick="checkSubmitStatus()"
回答by Kiley Naro
In the onclick event handler, if you return false the form will not submit. Try doing this:
在 onclick 事件处理程序中,如果返回 false 表单将不会提交。尝试这样做:
function checkSubmitStatus() {
if(validationSuccess==true)
{
return true;
}
else
{
return false;
}
}
<input type="submit" name="submit" value="Submit" onClick="return checkSubmitStatus()">
回答by JamesHalsall
I would refactor this slightly...
我会稍微重构一下......
function checkSubmitStatus() {
if( whatever==true) {
return false;
}
return true;
}
<input type="submit" name="submit" value="Submit" onClick="return checkSubmitStatus()">