Jan 08 2009 39

Alternate way to select ASP.NET server controls using jQuery

I guess that you know by now that if you use MasterPages in your applications client ID of controls will differ from "server" ID. That's because ASP.NET creates a new ID for controls on a page. So this is probably very familiar to you:

ctl00_cphContent_txtFirstName

You set the ID of the textbox to "txtFirstName" and ASP.NET adds "ctl00_cphContent_". Although there were some tries to prevent ASP.NET from generating unique ID's, I think it's better to use quick and "dirty" solutions :-)

So, how to select a server control using JS/jQuery? The usual way to select an element in JavaScript is to use server tags:

document.getElementById("<%=txtFirstName.ClientID %>");

You can use the same approach with jQuery:

$("#'<%=txtFirstName.ClientID %>'");

I always hated this. But, luckily, jQuery enables you to avoid server tags completely. Since we can search for element just by the part of the name, we can do the next:

$("[id$='_txtFirstName']");

This will find elements which id's ends with "_txtFirstName". But why the dash in the front of the name? This will ensure you selected the element by its full control ID, not just a part of it.

Pretty simple, isn't it? The only issue here would be if you have controls with the same name placed in different content pages.

So, what do you think? It this too dirty for you?

With support from

Written by Janko in Tutorials, tagged under ,

Share:

Comments are closed