Welcome to Professional ASP.NET - Chris Love's Official Blog Sign in | Join | Help

Chris Love's Official ASP.NET Blog

Chris Love's Helpful tips, tricks and pragmatic development knowledge for the ASP.NET world.
Add to Technorati Favorites


ASP Insider Follow Me On Twitter
Selecting ASP.NET Web Controls in JQuery

I have really gotten into using JQuery a lot this year, as I think just about anyone who is a web developer has in the past year or two. ASP.NET developers we inevitably will use Web Form controls, which have an Id property we define. This Id property ultimately gets munged into something much larger than the original value we defined. It is composed of all the parent controls of the control and of course its name. So a simple TextBox with the Id of 'txtMessage' gets changed to 'ctl00_ContentPlaceHolder1_txtMessage' (at least in this example) when it is rendered in the browser. That makes using the # selector syntax for finding this control in JQuery difficult. ASP.NET AJAX helps us with that by having it worked out in the $get('') function. But with JQuery you need to utilize a regular expression to do your selecting for you.

The following ASP.NET markup HTML can be used to demonstrated this situation:

<form id="form1" runat="server">
    <asp:TextBox runat="server" ID="txtMessage"></asp:TextBox>
    <button type="button" id="btnExtract">
        Extract</button>
</form> 

The following JQuery code will not work because there is no element with the name 'txtMessage' in the DOM.

<script type="text/javascript">
 $(function() {

            $('#btnExtract').click(
                function() {
                    alert($("#txtMessage").val());
                }
            );

        });
</script>

So you have to change the selector to use a regular expression to make the selection for you:

<script type="text/javascript">
 $(function() {

            $('#btnExtract').click(
                function() {
                    alert($("input[id$='txtMessage").val());
                }
            );

        });
</script>

The new selector tells JQuery to select any element that is an input with an id that ends with 'txtMessage'. So now this works and we can access the control's value or manipulate it anyway we want.

With ASP.NET 4.0 this sort of issue can be mitigated by controling the way the Ids are generated, but until then this is how you can solve the issue when selecting elements by Id in an ASP.NET page using Web Controls.

Posted: Wednesday, October 07, 2009 10:48 AM

by Chris Love

Comments

Leo said:

Couldn't you use: $('#btnExtract').click(function() { alert($("#<%= txtMessage.ClientID %>").val()); } );
# October 7, 2009 12:49 PM

Elijah Manor said:

Another option would be... <script type="text/javascript"> $(function() { $('#btnExtract').click( function() { alert($('#<%= txtMessage.ClientID %>').val()); } ); }); </script> Althought that is an option... I really don't like inline scriptlets in my jQuery or JavaScript code ;)
# October 7, 2009 12:54 PM

Josh said:

Can you write about how you design custom controls with id selectors that mitigate the multi-instance problem. (The control being used more than once in a page.)
# October 7, 2009 12:59 PM

Chris Love said:

Elijah, that is correct, but I really try to avoid inline scripts. I did it here for a consice example only.

Leo, I think that would extract everything with an id in the DOM, thinking wildcard, which is not what I want here.

# October 7, 2009 1:15 PM

Mike said:

Chris, "Elijah, that is correct, but I really try to avoid inline scripts. I did it here for a consice example only." Why do you avoid inline scripts?
# October 8, 2009 9:50 AM

Chris Love said:

Mike, performance issues. Every script tag is a blocking call and causes the browser to stop, process the script and then continue rendering content. That is part of the RFC that defines browser behavior.

# October 8, 2009 10:11 AM

Speednet said:

I have a couple of hacky solutions I use to solve this issue -- at least until ASP.NET 4.0 comes out. 1. Select by class name instead of ID. Use the CssClass property on the server control to set a class name, which can be treated like an ID value if you use a unique class name. For example: use the jQuery selector: alert($(".myUniqueId").val()); 2. Wrap the server control in a regular DOM object, and then select the element you're looking for within it. For example:
use the jQuery selector: alert($("#myUniqueId input").val()); -Todd
# October 8, 2009 12:23 PM

Speednet said:

Not sure why, but my comment was edited and the DOM elements showing how the elements are setup were stripped out. This is important, especially with the second example, as the jQuery expression alone does not explain the important aspect. Chris, I have not seen a lot of people using (or writing about) the second approach -- why strip it down to just the jQuery expression?
# October 8, 2009 2:00 PM

Brian said:

Chris -- weren't you paying attention to ASP.NET 4 talks? :) The CliendIdMode property in ASP.NET 4 is one of the best new features. I realize it's not RTM yet, but it will solve this problem.
# October 8, 2009 9:49 PM

Chris Love said:

Brian I am aware of that and I thought I mentioned that.

# October 9, 2009 5:23 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS