Q:

jQuery ID selector for nested elements in asp.net?

I'm can't figure out how this selector is correctly selecting the txtUsername element:
aspx:
<asp:Content ID="Content1" ContentPlaceHolderID="body" runat="Server">
    ...
    <div class="copy" style="float: left; width: 210px">
        <span class="copy" style="float: left; width: 210px">
            <asp:TextBox ID="txtUserName" runat="server" CssClass="ffield copy" Style="width: 198px;"></asp:TextBox>
        </span>
    </div>

jQuery:
var username = $('#body_txtUserName').val();

The ID for the asp:TextBox is txtusername not body_txtUserName, the only thing I can think of is that the txtusername is nested within a asp:Content element with ContentPlaceHolderID="body"
If this is true what is the significance of the underscore? I can't find any documentation on that syntax for jQuery selectors

A:

ASP.NET is modifying IDs at runtime, and it is best not to try and guess it. Instead you should either fix the ID, use generated one, or be smart about what you select on client side. Your options:

If your script is on the aspx page itself, you should be able to use ClientID like so:
$('#<%=txtUserName.ClientID %>')

If you are absolutely sure this control is the only one using this ID on the page, fix the ID with this control property:
ClientIDMode="Static"

$('#txtUserName')

You probably should not be relying on this, but generated IDs usually end with whatever ID you used on server side. So you can try to use "ends with" jQuery selector:
$('input[id$="txtUserName"]')

Again, this is not a very good idea, as it relies on assumptions about how ID generation works.

Assign another CSS class and use that. You do not need to define this class in your stylesheets, it is OK to use this technique for selection purposes only:
CssClass="ffield copy userNameText"

$(".userNameText")

