Using jQuery selectors to reference .Net controls
Overcome the problem of ids rendered differently to those declared in your code
You place a control onto your page:
<asp:Content ID="Content1" ContentPlaceHolderID="Content" Runat="Server"> <asp:TextBox Id="Firstname" Runat="Server" /> </asp:Content>The output is rendered as:
<input name="ctl00$Content$FirstName" type="text" id="ctl00_Content_FirstName" />In the example above, the disparity in the rendered id attribute occurs because the TextBox control has been placed within a Content control, as the Page object inherits a MasterPage.
So how can you robustly reference the control using client-side JavaScript, regardless where the control resides? Using jQuery it’s fairly trivial:
var $firstname = $("[id$=FirstName]");
This little snippet makes use of the jQuery attributeEndsWith selector, as documented here. Bare in mind that an array is returned, as any control with an id that ends in FirstName will be selected.
Comments
Please comment on this article. Constructive criticism, ideas, and corrections welcome. In fact, it does not even have to constructive. Feel free to take the p*ss.