Search code examples
asp.netjqueryexpressionclientidonclientclick

Why I cannot add clientId of my textBox in the mark-up here so that I can find it with jQuery?


Simply I am trying to pass the client Id of one textBox 'txtPersonId' for the client-click event so that I can traverse to that textBox control and pass its jQuery wrapper to the loadePerson() function.

This is how I decalre it in the aspx mark-up:

<asp:Button ID="btnSearch" runat="server" Text="ARA" OnClientClick="loadPerson(jQuery('#<%=txtPersonId.ClientID %>'))"/>

But when I render it, the

<%=txtPersonId.ClientID %>

place holder stays as it is and it is not replaced with the rendered control's client Id.

Any idea why this happens and how should I overcome that?


Solution

  • When I've had issues like this I've resorted to wrapping the entire expression in the brackets and building the result as a string. I assume that it's because the parser doesn't recognize the render block syntax embedded inside the string property.

     <asp:Button ID="btnSearch" runat="server" Text="ARA"
          OnClientClick='<%= "loadPerson(jQuery(\"#" + txtPersonId.ClientID + "\"))" %>' />
    

    I've long since moved on to keeping my javascript completely separate from my mark up, so I may be a little fuzzy on the exact details. If you wanted to separate your javascript from your mark up you could either add the handler with an explicit or relative DOM reference in a script block. Using the "ends with" selector matching on the id removes the need to find the explicit id, though you could also do that -- the example below shows both styles.

     <script type="text/javascript">
          $(function() {
              $('#' + '<%= btnSearch.ClientID %>').click( function() {
                    loadPerson( $('input[id$=txtPersonId]') );
              });
          });
     </script>