下面我有一个提交按钮和点击提交按钮时执行的jquery功能:
<p><input id="submitBtn" name="submitDetails" type="submit" value="Submit Details" onClick="return myClickHandler();" /></p>
<script type="text/javascript">
function myClickHandler()
{
if (validation())
{
showConfirm();
return true;
}
return false;
}
</script>
现在,您可以看到是否满足validation()函数,然后它将执行showConfirm()函数,此函数将执行以下确认框:
function showConfirm()
{
var confirmMsg=confirm("Make sure that your details are correct, once you proceed after this stage you would not be able to go back and change any details towards Questions, Options and Answers for your Assessment." + "\n" + "\n" + "Are you sure you want to Proceed?" + "\n" );
if (confirmMsg == true)
{
submitform();
return true;
}
else
{
return false;
}
}
function submitform()
{
var fieldvalue = $("#QandA").val();
$.post("insertQuestion.php", $("#QandA").serialize(), function(data)
{
var QandAO = document.getElementById("QandA");
QandAO.submit();
});
alert("Your Details for this Assessment has been submitted");
}
我的问题是这个。如果用户在确认框中单击“确定”,则它会提交页面,这很好。但是如果用户点击取消,那么它不应该提交页面。问题是,即使点击了取消按钮,它也在提交页面。为什么是这样?
更新:
我在下面尝试过这段代码,但仍然没有运气:
function myClickHandler()
{
if(validation())
{
return showConfirm();
}
return false;
}
答案 0 :(得分:6)
if(validation()){
showConfirm();
return true;
}
您对showConfirm();
的回复不做任何处理。完成该功能后,您只需return true
。试试return showConfirm();
。
<小时/> 如果用户在
showConfirm()
函数中单击“取消”,则它不执行submitform()
函数,showConfirm()
函数返回false。但由于您没有捕获该返回值,myClickHandler()
函数返回true,这不会阻止提交表单。
您可能只希望myClickHandler()
函数始终返回false,并让表单提交由showConfirm()
函数处理。
<小时/> 的更新:强> 这是(IMO)更好的方法。我不确定你是否需要使用AJAX(
$.post
调用)。试试这个:
<form id="QandA" action="somepage.php" method="POST" onsubmit="return myClickHandler()">
<!--
...
-->
<input type="submit" id="submitBtn" name="submitDetails" value="Submit Details" />
</form>
<script type="text/javascript">
function myClickHandler()
{
if (!validation())
return false;
if (!confirm("Make sure that your details are correct, once you proceed after this stage you would not be able to go back and change any details towards Questions, Options and Answers for your Assessment." + "\n" + "\n" + "Are you sure you want to Proceed?" + "\n" ))
return false;
// if all you're trying to do is submit the form to insertQuestion.php,
// then skip this AJAX call. I'm assuming that you need to do something
// on the server before submitting the form. if not, skip this.
$.ajax({
url: "insertQuestion.php",
data: $("#QandA").serialize(),
async: false
});
return true;
}
</script>