Reputation: 7
I'm using Visual Studio 2012 to build a web application using ASP.NET.
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
The above code is for a textbox
<script type="text/javascript">
function validate2() {
if (document.getElementById("<%=textBoxToolID.ClientID%>").textContent=="") {
alert('textbox1 cannot be empty');
return false;
}
}
</script>
The above is the code I used for client side validation of null textbox.
<asp:Button ID="buttonNew" runat="server" Text="New" Width="75px" OnClick="buttonNew_Click" OnClientClick="validate()" />
I'm calling onclientclick property to call the validate function at the time of button click event. The problem is even there is content in the textbox, the alert message is triggered.
What is it that I'm doing wrong?
Upvotes: 0
Views: 345
Reputation: 35514
asp.net has it's own Controls for validating user input. You might want to read up on those.
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic"
ControlToValidate="TextBox1" ErrorMessage="textbox1 cannot be empty" ValidationGroup="myGroup1">
</asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" ValidationGroup="myGroup1" Text="Button 1" OnClick="Button1_Click" />
<asp:TextBox ID="textBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Display="Dynamic"
ControlToValidate="TextBox2" ErrorMessage="textbox2 cannot be empty" ValidationGroup="myGroup2">
</asp:RequiredFieldValidator>
<asp:Button ID="Button2" runat="server" ValidationGroup="myGroup2" Text="Button 2" OnClick="Button2_Click" />
Upvotes: 0
Reputation: 831
<script type="text/javascript">
function validate2() {
if (document.getElementById("<%=textBoxToolID.ClientID%>").value=="") {
alert('textbox1 cannot be empty');
return false;
}
}</script>
it's .value
Upvotes: 1