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.

Share This Article With Your Friends!

Googles Ads Facebook Pixel Bing Pixel LinkedIn Pixel