handling jQuery on ASP.NET ID

jQuery is a very powerful library for making good interaction on your web application. However in ASP.Net development environment there is a problem that I found when selecting the ID of an ASP.Net control.

Usually we can select the id of specific html tag by using this

$(document).ready(function(){
$('#IDofSpecificTag').click(function() {
// do implementation here
)};
});

But when we want to access the ID of ASP.Net Control we cannot simply select the ID of the control, as when it rendered in html page (after it compiled) it will have some attachment (prefix) on the id.
For example, my asp:textbox with id txtBarcode it renders as ContentPlaceHolder1_txtBarcode in the generated html.

The Solution:

$(document).ready(function(){
$('# <%=
IDofSpecificTag.ClientID %>').click(function() {
// do implementation here
)};
});

OR


$(document).ready(function(){
$("*[id$='IDofSpecificTag']")..click(function() {
// do implementation here
)};
});

I prefer the first solution as it is very simple in implementation, however it is not very good practice to mix up between ASP.Net tag with javascript..
I hope this will be useful for people who are still learning how to use jQuery in ASP.Net πŸ™‚

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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