[英]OnClientClick not working
I am having some problem with OnClientClick. 我在使用OnClientClick时遇到问题。
I added a button into my webform like this. 我像这样在我的网络表单中添加了一个按钮。
<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()" />
And i am writing a javascript inside <head>
immediately after the <title>
. 我在
<title>
之后立即在<head>
编写了一个javascript。
<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>
TextBox1
and TextBox2
are the Id's of two textboxes. TextBox1
和TextBox2
是两个文本框的ID。
But when i click on Submit button, OnClick is firing but OnClientClick is not firing. 但是,当我单击“提交”按钮时,OnClick会触发,但OnClientClick不会触发。
Whats the problem ? 有什么问题 ?
Please help. 请帮忙。
When taking the ID from the textboxes, you'll have to use <%=TextBox1.ClientID%>
in your javascript. 从文本框中获取ID时,您必须在JavaScript中使用
<%=TextBox1.ClientID%>
。
And you should also return false
from the validate-function when an error occurs. 当发生错误时,您还应该从validate-function
return false
。
Replace your javascript with: 将您的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;
}
}
Try this way:- 尝试这种方式:-
document.getElementById("<%=TextBox1.ClientID%>").value
document.getElementById("<%=TextBox2.ClientID%>").value
The first thing i see, is that you are using "<%=TextBox1%>"
without the .ClientID
, which is what recognizes the texbox on the client side. 我看到的第一件事是,您正在使用不带
.ClientID
"<%=TextBox1%>"
,这是客户端可识别texbox的内容。 naturally, without id, you javascript cannot find the object (and probably throws an exception as well) 自然地,没有ID,您的javascript找不到对象(并且可能还会引发异常)
(document.getElementById("<%=TextBox1%>").value == "")
will render as 将呈现为
(document.getElementById("System.Web.UI.WebControls.TextBox").value == "")
. (document.getElementById("System.Web.UI.WebControls.TextBox").value == "")
。
so try to use document.getElementById("<%=TextBox1.ClientID%>").value
in the javascript function. 因此请尝试在JavaScript函数中使用
document.getElementById("<%=TextBox1.ClientID%>").value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.