Need assistance with jQuery and ASP.NET want to show/hide a panel on click of a button, but the postbacks mess it up

StackOverflow https://stackoverflow.com/questions/9176920

Question

RESOLVED

how do i set question to resolved? lol

Anyways here is the sollution, I had my friend help me and he did it!

First since as I said I was using an update panel the jQuery didn't register the partial postbacks from it and that was the main problem. A slightly lesser problem why it didn't work without an update panel was the 1 and 0 values in the function on click being swapped mistakenly.

So first we did an override on the OnInit method, but you can put the same code in pageload too(except the call to base on init code ofc) :) :

protected override void OnInit(EventArgs e)
    {


        base.OnInit(e);

        prikazi.Attributes.Add("onclick", "return LinkKlik();");


        ScriptManager.RegisterStartupScript(this, this.GetType(), "init", "checkComponent();", true);
    }

Where we register a script to run every time the page gets reinitialized, even with async postbacks :) and we add the click function to the linkbutton here as well.

the jquery code is as follows:

function checkComponent() {
    //
    if (document.getElementById('hidTracker').value == '1') {
        $(".sokrij").show();

    }
    else {
        $(".sokrij").hide();
    }
}

function LinkKlik() {

    var panel = $("#fioka").find(".sokrij");

    if (panel.is(":visible")) {
        panel.slideUp("500");
        $('#hidTracker').attr("value", "0");

    }
    else {
        panel.slideDown("500");
        $('#hidTracker').attr("value", "1");

    }
    // that's it folks! (return false to stop the browser jumping the the '#' link
    return false;
}

It's basically the same as before, just divided in 2 functions linked to events by the override above.

one last thing, you need these:

        <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <script type="text/javascript" src="drawer.js"></script>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
            <asp:HiddenField ID="hidTracker" runat="server" Value="0" />
            <div id="fioka">
                <asp:LinkButton runat="server" href="#" ID="prikazi">Click This to show/close</asp:LinkButton>
                <div class="sokrij" id="sokrij">
                    HIDE THIS!!!
                </div>
            </div>
            <asp:Button ID="Button1" runat="server" Text="Button" />
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="prikazi" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>

It even works inside the update panel. the button is there to generate postbacks, and you can even put one outside to generate real postbacks outside the update panel. The value of the state is recorded in the hidden field, and the linkbutton is the one we use to show/hide. Cheers if anyone ever needs this, cause i saw lots of posts about the same thing but none of them answered it.

Thanks guys for answering, especially CRAB BUCKET

I would give u all +rep if i could but as u can see just starting.

I have a control in which i have various elements that do postback. I have that control in my main page in an update panel, and it works great. What i want to do is hide half of the elements and to be able to show them only when button is clicked. I managed to find some jQuery drawers and it looked fine, but whenever I opened the panel and changed an element which had a postback to call a c# function on click or value change the drawer is opened (no matter if i press the open drawer link).

my elements have to have postbacks! and i need that drawer show/hide thingie to hide half of them...

here's what I have on the drawer so far, by putting together some code myself. As I said with this code it i click any button that causes post back, the drawer is opened after the postback even if i didn't click the open drawer link. Other than that it works ok between postbacks, but I have to have it working even with postbacks!

$(function () {

$(".sokrij").hide(),


$("#prikazi").live("click", function (evt) {
        evt.preventDefault();

        $("#fioka").find(".sokrij").each(function () {

            if ($(this).is(":visible")) {
                $(this).slideUp("500");
            }
        });

        if ($(this).next().is(":hidden")) {
            $(this).next().slideDown("500");
        }

        return false;
    });


});

I need a way to make the postbacks not influence the state of the drawer. If it is open I want it to stay open after a postback, and if it is closed to stay closed after postback. So that means I need it to remember it's state and check it after every postback!

Here is my tag structure.

<div id="fioka">
    <a href="#" ID="prikazi">Click This to show/close</a>
    <div class="sokrij">
</div>
</div>

MAJOR EDIT:

Here is what I have now, after the input from Crab Bucket:

tag structure:

<input type="hidden" ID="hidTracker" value="0" />    
<div id="fioka">
             <a href="#" ID="prikazi">Click This to show/close</a>
             <div class="sokrij">
         </div>
         </div>

and that's all inside an update panel in which there are buttons that generate postbacks, but those postbacks do not refresh the main page, they are contained inside the update panel.

and the jQuery code is thus far:

$(document).ready(function () {

if ($('#hidTracker').val() == '1') {
    $(".sokrij").show();
}
else {
    $(".sokrij").hide();

}



  $("#prikazi").live("click", function (evt) {
      evt.preventDefault();

      var panel = $("#fioka").find(".sokrij");

      if (panel.is(":visible")) {
          panel.slideUp("500");
          $('#hidTracker').val('1');
      }
      else {
          panel.slideDown("500");
          $('#hidTracker').val('0');
      }

      return false;
  });


});

So it now works like this: On the site load, it shows the panel (drawer) closed. If i click the link to show/hide panel it works superb. But after one of the buttons generates a postback it refreshes the panel and it shows up OPEN every time a postback is generated. After the postback I can still use the open/close link to open/close it and that works well, but i need a way to save the sate the panel was before the postback and set it in that state after the postback.

The code crab bucket provided with the hidden field should work for that too, but it doesnt, and i think i need some way to execute the check for whether the panel was open or closed after a postback. as it is the check only happens on the page load, but not after postbacks!!!

Was it helpful?

Solution

You need to do the state tracking yourself. I've used my own hidden field for this i.e.

<input type="hidden" ID="hidTracker" value="0" />

and at the top of your function

if($('#hidTracker').val() == '1')
{
    $(".sokrij").show();
}
else
{
    $(".sokrij").hide(); 

}

then change your main function body to track state manually

$("#fioka").find(".sokrij").each(function () 
{              
    if ($(this).is(":visible")) 
    {                 
       $(this).slideUp("500");    
       $('#hidTracker').val('0');          
    }         
});          

if ($(this).next().is(":hidden")) 
{             
   $(this).next().slideDown("500");        
   $('#hidTracker').val('1');          

} 

BUT

This is only going to work for one panel - which isn't your case. So you are going to have to finnese this process to link the state to the id of the panel being shown hidden.

I've done this before by using the same principle but recording a JSON string in the hidden field then rehydrating it gives the ability to add structure key/value information to record the state

The JSON in your hidden field might look like this for two panels

{"panelState": [{ID:"pnl1", "State":"1"}, {ID:"pnl2", "State":"0"}]}

and here is a json parser to help you construct and rehydrate the strings.

It's going to a a bit of work to get it going but this is the start. If i get time I will flesh it out a bit more but i can't promise - sorry

EDIT

To adapt for one panel try

var panel = $("#fioka").find(".sokrij");

if (panel.is(":visible"))      
{                         
    panel.slideUp("500");            
    $('#hidTracker').val('1');               
}  
else
{
    panel.slideDown("500");            
    $('#hidTracker').val('0');       
}

Don't forget to wrap all your code in

$(document).ready(function(){

  //all my code

});

Otherwise the DOM isn't guaranteed to be loaded and the code may not execute correctly

EDIT 2

It's hard to get the show hide code trackering javaScript but this strange function hooks into the update panel and will fire when the update panel posts back. This will allow your update panel to track the panel state

 Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) {

     if($('#hidTracker').val() == '1') 
     {     
         $(".sokrij").show(); 
     } 
     else 
     {     
         $(".sokrij").hide();   
     } 

});

Hope it helps

OTHER TIPS

So if you want something to be hidden:

.sokrij
{
    display:none;
}

then when you want it to be shown:

$(".sokrij").css("display","";

Edit: I misunderstood your needs. If you need to save the info use a session variable or something similar.

if(Session["state"] != null)
    string state = Session["state"].ToString();

if(state  == "0")
{
    $(".sokrij").hide();
}

if (state == "1") { $(".sokrij").hide(); Session["state"]="0"; } }

Of course you can change the strings to integers or boolean or whatever.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top