Love Aajkal
Love Aajkal

Reputation: 13

How to hide/show inside a repeater?

I am trying to hide/show a div on anchor click, but that doesn't work.

I have repeater, and in it there are so many posts. There are bound images, descriptions and comments (anchor tag).

When I click on a comment, the associated div will be displayed.

<a href="#" onclick="$('#<%= divSearch.ClientID%>').toggle('medium');return false;">Show Search</a>
<div class="widget-content" id="divSearch" runat="server" style="display: none; background-color: #EEEEEE;">Content goes here</div>

It works perfectly outside of repeater item template, but when I placed it inside the repeater, then it doesn't work

Upvotes: 0

Views: 1548

Answers (3)

Racil Hilan
Racil Hilan

Reputation: 25351

Inside the template control, you need to use <%# instead of <%=:

<a href="#" onclick="$('#<%#Container.FindControl("divSearch").ClientID%>').toggle('medium');return false;">Show Search</a>

Upvotes: 0

hardkoded
hardkoded

Reputation: 21617

I think the cleanest way to implement this is in the ItemDataBound event.

Markup

<a href="#" runat="server" id="showSearch">Show Search</a>
<div class="widget-content" id="divSearch" runat="server" style="display: none; background-color: #EEEEEE;">Content goes here</div>

Event

protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var link = e.Item.FindControl("showSearch") as HtmlControl;
        link.Attributes["onclick"] = $"$('{e.Item.FindControl("divSearch").ClientID}').toggle('medium'); return false;";
    }
}

Upvotes: 0

VDWWD
VDWWD

Reputation: 35514

The other 2 answers given are forgetting that there are more that one divSearch in a Repeater, so you cannot directly access them in the aspx. For that you need to use FindControl, this can be done inline. You have to find the Panel inside the Container and get that ClientID.

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>

        <asp:Panel ID="divSearch" runat="server" style="display:none">
            <%# Eval("value") %>
        </asp:Panel>

        <a href="#" onclick="$('#<%# Container.FindControl("divSearch").ClientID %>').toggle('medium');return false;">Show</a>

    </ItemTemplate>
</asp:Repeater>

Upvotes: 1

Related Questions