I am having some problem with 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>
.
<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.
But when i click on Submit button, OnClick is firing but OnClientClick is not firing.
Whats the problem ?
Please help.
When taking the ID from the textboxes, you'll have to use <%=TextBox1.ClientID%>
in your javascript.
And you should also return false
from the validate-function when an error occurs.
Replace your javascript with:
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. naturally, without id, you javascript cannot find the object (and probably throws an exception as well)
(document.getElementById("<%=TextBox1%>").value == "")
will render as
(document.getElementById("System.Web.UI.WebControls.TextBox").value == "")
.
so try to use document.getElementById("<%=TextBox1.ClientID%>").value
in the javascript function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.