Access an ASP.NET control on a MasterPage using jQuery

I must have been asked this question numerous times -- How do I access an asp.net control kept in the master page using jQuery? Here’s one of the ways of how to populate the value of an ASP.NET TextBox kept in a MasterPage using jQuery

MasterPage

<%@ Master Language="C#" AutoEventWireup="true"
CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!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>Access Control using jQuery</title>
<
asp:ContentPlaceHolder id="head" runat="server">
</
asp:ContentPlaceHolder>

<
script src="Scripts/jquery-1.3.2.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$("input[id$='txtName']").val("Text Added using jQuery");
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

</
asp:ContentPlaceHolder>
</
div>
</
form>
</
body>
</
html>



ContentPage

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"

AutoEventWireup="true" CodeFile="MasterPage.aspx.cs" Inherits="MasterPage"%>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</
asp:Content>

<
asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"

Runat="Server">

<
asp:TextBox ID="txtName" runat="server"></asp:TextBox>

</
asp:Content>

Note how we selected the MasterPage using the $("input[id$='txtName']") . This is because the TextBox in the MasterPage gets renamed as shown below:

<input name="ctl00$ContentPlaceHolder1$txtName" type="text" id="ctl00_ContentPlaceHolder1_txtName" />

On running the page, the textbox gets populated using jQuery

image

Check out my other ASP.NET jQuery articles.



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

2 comments:

Anonymous said...

Thanks a lot buddy.
It really saved my lot of efforts.

Thanks again.

Umesh Bhavsar

Prem Kumar said...

Thanks a lot!!!!

It really helped me.

Thank once again

Regards,
Prem Kumar.