简体   繁体   中英

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

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:

  1. If your script is on the aspx page itself, you should be able to use ClientID like so:

     $('#<%=txtUserName.ClientID %>') 
  2. 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') 
  3. 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.

  1. 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") 

It is not related to jquery. It is because the client Id and actual Id may differ. body_txtUserName is client Id in your case. Try:

 $('#<%= txtusername.ClientID %>');

There are a few options here depending on where your actual Javascript is located.

Javascript within an ASPX file

This one is easy as you can use the ClientID property to resolve the appropriate client-side ID for the Control :

// This will resolve the client-side ID as expected
$('#<%= txtUserName.ClientID %>');

This won't work if your jQuery code is contained within an external Javascript file though.

Javascript within an external file

If your Javascript is contained within an external file, you could consider using the the jQuery "ends-with" selector $= that would match an element that ended with the appropriate ID :

$('[id$="txtUserName"]')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM