0
votes

I am using a toggle link to show and hide some page content on a search page. The toggle is set to hide on page load. Function works great but I will need to remember the toggle state on form submit so that if the user decides to edit the initial search the state is remembered.

Here is the working function:

$(document).ready(function(){

   $(".slidingDiv").hide();
   $(".show_hide_search").show();

   $('.show_hide_toggle').on('click', function(e){
       e.preventDefault();

       var self    = this,
           sliding = $(this).closest('div').next('.slidingDiv').slideToggle(function(){
               $($(self).children()[0]).text(function(_,txt) {
                    return txt == "–" ? "+" : "–";
               });
           });
    });
});

And the HTML:

<div class="show_hide_toggle">
    <a href="#" class="show_hide_search" id="plus">+</a>    
    <div class="show_hide_search2">More</div>
</div>  

<div class="slidingDiv" style="display: block;">
      <h2>Content One</h2>
</div>

This is how I remember the session for the form elements if it helps:

<?php echo ($_SESSION['save_srch']['name1'] == 'name')?'selected="selected"':'';?>

Here is a JSFiddle: http://jsfiddle.net/Bradg/eBfxB/11/

1
store a boolean in the session and based on what it is show/hide?starvator
You'll have to store it using AJAX. Set the session variable via AJAX.ChrisG

1 Answers

1
votes

Seems like you have a couple options. As mentioned in the comments above you could add something to the click handler of your toggle to make an AJAX call to the server and store the value in the session immediately.

However your original question was how you could store it on form submit (post). My suggestion if you don't want to go the AJAX route is to add a hidden input control to your markup with a true/false value for the state of the toggle. Any time the toggle is clicked, toggle the value of the hidden control also. When you submit the form, just inspect the value of the hidden control and store the value in session as you desire.

The downside to this approach is if for some reason the browser lost state before the form submit, you would not store the value immediately. So it's possible in some scenarios (browser crash, navigate away) that the form would not be submitted and thus the value of the toggle not stored. So you will have to decide which approach is OK for your scenarios.