Click here to Skip to main content
15,889,096 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to put some validation on my registration form in asp.net using JavaScript. but it didn't work the way i want. i want that if user leave a text-field empty an alert message pops up and then set force user to fill that field by using focus.

I write this code, but the problem is that after showing alert message, it didn't set focus on TextBox2.

C#
<asp:TextBox ID="TextBox2" runat="server" onblur="ValidateTextNotNull()"></asp:TextBox>


JavaScript
function ValidateTextNotNull()
     {
         var Firstname = document.getElementById('TextBox2').value;
         var textLength = Firstname.length;
         if (textLength == 0) {
             alert("show your message");
             document.getElementById('TextBox2').focus();
         }

     }
Posted

1 solution

replace document.getElementById('TextBox2') with document.getElementById('<%=TextBox2.ClientID%>')

Please read the Documentation[^]

Quote:
When a Web server control is rendered as an HTML element, the id attribute of the HTML element is set to the value of the ClientID property. The ClientID value is often used to access the HTML element in client script by using the document.getElementById method.
 
Share this answer
 
v2
Comments
Muhammad Taqi Hassan Bukhari 3-May-14 6:36am    
Problem solved. but Can you give me some explanation for <%=TextBox2.ClientID%>
DamithSL 3-May-14 6:46am    
check my update

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900