简体   繁体   中英

Find control created in Code-behind using jQuery

I want to be able to access a label control in jQuery that was created in the codebehind.

I have added controls to my page in the codebehind like so

        Label L = new Label();
        L.ID = "txt" + i;
        L.Text = dr["category_name"].ToString();
        L.CssClass = "heading";
        divCat.Controls.Add(L); 

Is it possible to find these controls via ID or an alternative option in jQuery? The following gives an error saying there is no such control:

$(function () {
  $(".hoverlabel").hover(function () {
    $("#<%=txt1.ClientID %>").show();
  });

});

I am not sure will it work or not.
You can take the benefit of the ClientIDMode="Static" eg.

<asp:TextBox ID="txtEcho2" runat="server" ClientIDMode="Static" /> 

In your case

    Label L = new Label();
    L.ID = "txt" + i;
    L.Text = dr["category_name"].ToString();
    L.CssClass = "heading";
    divCat.Controls.Add(L); 
    L.ClientIDMode= ClientIDMode.Static;

and your jquery function

    $(function () {
        $(".hoverlabel").hover(function () {
        $("#txt1").show();
       });
    });

You can't do what you're trying to do.. that way.

You're trying to use a string as an object within code. Take this normal C# for example:

string myString = "HelloString";
string lowerString = HelloString.ToLower(); // This won't work..

That is the equivalent of what you're trying to do.

The workaround is using FindControl :

$(function () {
    $(".hoverlabel").hover(function () {
        $("#<%= FindControl("txt1").ClientID %>").show();
    });
});

This will find a control based on the ID you've dynamically assigned it.

Assuming the code-behind actually renders an html <label> , your jQuery could be something like:

$(function () {
  $(".hoverlabel").hover(function () {
    $("label.heading").show();
  });
});

Simply assign an additional "identifying CSS class":

var L = new Label();
L.ID = "txt" + i;
L.Text = dr["category_name"].ToString();
L.CssClass = "heading myLabel"; // Set multiple classes separated by spaces
divCat.Controls.Add(L); 

Then you can get your control with this jQuery statement:

$(function () {
  $(".hoverlabel").hover(function () {
    $(".myLabel").show();
  });
});

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