tags:

views:

17

answers:

1

I am trying to add some jquery to span with a class added to it. I am using asp.net and trying to use RegisterClientScriptBlock to attach the below code to my element. "cphMain_ed1" is hardcoded in this example however I would normally been passing a parameter here just for the ease of this.

   <script language="javascript" type="text/javascript">
    $(function () {
        $('.closeButton').click(function () {
            alert('called ok');
            $("cphMain_ed1").slideUp();
        });
    });
</script>

My c# code looks like this

  String csName = string.Format("ButtonClickScript_{0}", this.ID);
        Type csType = this.GetType();

        ////// Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = Page.ClientScript;
        StringBuilder csText = new StringBuilder();
        // csText.Append("<script  type=\"text/javascript\"> HidePanel('" + this.ID + "')");
        csText.Append("<script  type=\"text/javascript\">DoIt()");
        csText.Append("</script>");
        cs.RegisterClientScriptBlock(csType, csName, csText.ToString());

What am I doing wrong as the function is not been attached to the span with the class "closeButton"

ANy help would be great!!

+1  A: 

If you add a class to that user control container you want to hide, so your result is something like this:

<div class="container">
  <span class="closeButton">Close</span>
  Other content here
</div>

Then you can do away with IDs and code-behind code altogether, and reduce your jQuery down to this:

$(function() {
  $('.closeButton').click(function () {
    $(this).closest('.container').slideUp();
  });
});

Instead of relying on an ID, it just finds the thing you want to hide in relation to the .closebutton. In this case we're using .closest() to get the nearest element up the tree matching the selector...the class that was added to the container you want to close. There are other functions to find things relatively as well, the tree traversal functions, in case you have other situations where this can save you some code.

Nick Craver
Do I need to do some extra steps when working with a usercontrol? I have my usercontrols inside an asp.net panel <asp:Panel ID="ed1" runat="server" CssClass="PanelArea"> <uc1:ucEducationDetails ID="ucEducationDetails1" runat="server" DoSomething="DoSomething" /> </asp:Panel> <asp:Panel ID="ed2" runat="server" CssClass="PanelArea Hidden" > <uc1:ucEducationDetails ID="ucEducationDetails2" runat="server" /> </asp:Panel>
I then added the above function into my page however when I use firebug my span class "closeButton" doesnt have any jquery attached to it?
@diver-d - Can you post or link to the rendered HTML? Are you trying to close each user-control individually, or close the whole panel when any of the close buttons are clicked?
Nick Craver