OnClientClick无法正常工作

Ran*_*ddy 0 .net c# asp.net

我在OnClientClick上遇到了一些问题.

我在这个webform中添加了一个按钮.

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
        style="top: 307px; left: 187px; position: absolute; height: 26px; width: 90px" 
        Text="Submit" OnClientClick="return validate()" />
Run Code Online (Sandbox Code Playgroud)

我正在写一个javascript里面<head>的内容<title>.

<script language="javascript" type="text/javascript">
    function validate() {
        if (document.getElementById("<%=TextBox1%>").value == "") {
        alert("textbox1 should not be empty");
        }
        else if(document.getElementById("<%=TextBox2 %>").value==""){
        alert("textbox2 should not be empty");
        }
                        }
</script>
Run Code Online (Sandbox Code Playgroud)

TextBox1并且TextBox2是两个文本框的Id.

但是,当我单击"提交"按钮时,OnClick正在触发,但OnClientClick未触发.

有什么问题 ?

请帮忙.

NoL*_*ing 6

从文本框中获取ID时,您必须<%=TextBox1.ClientID%>在javascript中使用.

并且您还应该return false在发生错误时使用validate-function.

用以下内容替换您的javascript:

function validate() {
    if(document.getElementById('<%=TextBox1.ClientID%>').value == '') {
        alert('Textbox1 should not be empty');
        return false;
    }
    if(document.getElementById('<%=TextBox2.ClientID%>').value == '') {
        alert('Textbox2 should not be empty');
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)