May 1, 2009

How to Select the Asp.Net server controls + JQuery

People while using 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:


You set the ID of the textbox to "txtName" 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("<%=txtName.ClientID %>");

You can use the same approach with jQuery:

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

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:


This will find elements which id's ends with "_txtName". 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.

No comments: