8. January 2009 20:22 by Janko in Articles | tags: ,

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?

If you liked this article why don't you share it:

Stumble it delicious Digg it Float it DZone it Kick it Bump it E-mail

Comments

Pingbacks and trackbacks

  1. Trackback from DotNetKicks.com Alternate way to select ASP.NET server controls using jQuery
  2. Trackback from My.Mountains[] What kept me busy recently #1

Add comment

   
        Country flag
biuquote
Loading