preventDefault()提交表单 [英] preventDefault() submitting form
问题描述
好吧,我一般来说对jQuery和JavaScript还是陌生的.我有一个表单,我想要做的是让表单运行一个函数来确保所有内容都在其中,并且所有变量都是正确的,然后提交.我在提交按钮上使用了onclick
值,并让它运行使用preventDefault()
的函数.我不确定即时通讯是否使用正确,但似乎无法正常工作.这就是我所拥有的,当您单击提交时,即使if语句为false,它也只会提交.
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.
function checkSubmitStatus() {
$("#myform").submit(function(event){
if( whatever==true) {
event.preventDefault();
}
});
}
<input type="submit" name="submit" value="Submit" onClick="checkSubmitStatus()">
谢谢!
推荐答案
通过将$("#myform").submit(...)
放在checkSubmitStatus()
函数中,您可以在单击按钮并且表单已经提交之后附加提交处理程序.试试这个:
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:
<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>
这篇关于preventDefault()提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!