首页 > 解决方案 > 在 JavaScript 函数中检索“confirm()”值时出现 Asp.net 问题

问题描述

我想知道为什么 Java Script 函数没有正确返回 Confirm 值。

我有这个按钮:

<asp:Button ID="btnSaveAgreement" runat="server" UseSubmitBehavior="false" Text="Save" OnClientClick ="ConfirmSaveWithoutSendEmail(this);" />

我有这个 Java 脚本功能:

 function ConfirmSaveWithoutSendEmail(btnToDisableWhileSubmitting)
    {           
        var IsPanelToSendEmailVisible = document.getElementById('<%= hfIsSendEmailPanelVisible.ClientID%>').value; 

        if (IsPanelToSendEmailVisible > 0)
        {
            //This section takes a confirmation "Ok/Cancel" to submit or not 
            //the data, the problem is that if I choose "Cancel", the code 
            //on the button is executed, the behavior I would except is such 
            //that selecting "Cancel"  the code on my button is not 
            //executed.

            return confirm("Do you want to save without send email?");
        }
        else
        {                
            //this section disable the button while submitting information, 
            //this section works fine.

            if (!Page_ClientValidate())
                return false;

            btnToDisableWhileSubmitting.disabled = true;
            btnToDisableWhileSubmitting.value = 'Saving...';
            return true;
        }
      }

为什么选择的确认值总是被认为是真的?

我想知道我错过了什么。

标签: javascriptasp.net

解决方案


问题是因为您在OnClientClick属性中设置的代码实际上并没有返回任何内容,它只是执行ConfirmSaveWithoutSendEmail函数但实际上并未使用它的返回值。您还应该进行设置UseSubmitBehavior="true",以便它在点击时提交您的表单。尝试这个:

<asp:Button ID="btnSaveAgreement" runat="server" UseSubmitBehavior="true" Text="Save" OnClientClick="return ConfirmSaveWithoutSendEmail(this);" />

else您的声明部分也if将不起作用,因为您在它能够提交表单之前禁用了该按钮。如果出现以下表单,您将需要禁用该submit表单:

document.getElementById('yourFormId')
    .addEventListener('submit', function() { 
        var submitBtn = document.getElementById('<%= btnSaveAgreement.ClientID %>');
        submitBtn.disabled = true;
        submitBtn.value = 'Saving...';
    });

推荐阅读