In this article I will explain with an example, how to find and get value of TextBox in UserControl i.e. WebUserControl (ASCX) from Parent Page (ASPX) using JavaScript in ASP.Net.
The UserControl
Following is the HTML Markup of a simple UserControl which consists of a TextBox for capturing name of the User.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UC_Name.ascx.cs" Inherits="UC_Name" %>
Name: <asp:TextBox ID = "txtName" runat="server" />
The Page
The following HTML Markup of the ASPX Page contains the UserControl (discussed earlier) and a Button.
The button has an OnClientClick event handler which executes a JavaScript function which validates the TextBox txtName present inside the UserControl ucName.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/UC_Name.ascx" TagName="Name" TagPrefix="uc" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<uc:Name ID="ucName" runat="server" />
<br />
<br />
<asp:Button Text="Validate" runat="server" OnClientClick="return Validate()" />
</form>
</body>
</html>
The Problem
When you place an ASP.Net control inside some UserControl then the HTML ID of control placed inside the UserControl changes.
And hence JavaScript is unable to find the control with its original assigned ID.
For example a TextBox with ID txtName in a UserControl with ID ucName will have the HTML ID as ucName_txtName. The following View Source of the page displaying this behavior.
The Solution
Solution to this problem is to make use of Embedded Code Blocks to find the TextBox inside the UserControl in order to determine its ClientID property.
In the following JavaScript function, the TextBox is referenced using ASP.Net FindControl method and then its ClientID is used inside the document.getElementById method to get the reference of the TextBox.
<script type="text/javascript">
function Validate() {
var txtName = document.getElementById('<%=ucName.FindControl("txtName").ClientID %>');
if (txtName.value == "") {
alert("Please enter name!");
return false;
}
return true;
}
</script>
Screenshot
Demo
Downloads