0

嗨,下面我有一个提交按钮和一个在单击提交按钮时执行的 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;
}
4

1 回答 1

6
if(validation()){
    showConfirm();
    return true;
}

您不会对 from 的返回做任何事情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>
于 2012-09-17T16:42:15.823 回答