Multiple Ways To Access Asp.Net TextBox Control Using jQuery


Let’s take an example of textbox control.

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

When ASP.NET renders server side controls it gives them unique client ids which are different from their server ids and if you check view source of your ASP.NET page

you will find ids familiar to following.

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

This id can be even more lengthy if you are using Master pages in your ASP.NET website. So how you can access these controls in JQuery. There are some options

available using which we can select the above textbox control.

1) Using ClientID

$('#<%= txtName.ClientID %>')

Note : you can only use it in .aspx pages, not in external .js files.

2) Using attribute selectors

$('[id$=txtName]') /* id which ends with the text 'txtName' */
$('[id*=txtName]') /* id which contains the text 'txtName' */

3) Using CssClass

Highly recommended. Because selectors using classes are clean and uncomplicated. In case you are wondering, CssClass for .net controls is the same as class for traditional html controls.

<asp:TextBox runat="server" ID="txtName" CssClass="myclass" />
$('.myclass')

4) Use ClientIDMode=”Static”

This is introduced in .NET Framework 4.0, on the control so that it’s ID will stay unchanged.

<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static"  />
$('#txtName')

Hope this will help !!!

Jay Ganesh

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s