Question

I have written a cascading drop down list using JQuery. The code that I have written works; the cascading list when changed, updates the cascaded-to list. BUT when I navigate away from the page and then press the back button on the browser, the CASCADED drop down list loses its values. Here is my code (the category list populates the products list when changed):

<select id="CategoryList" onchange="CategoryList_OnChange()">
    <option value="" selected="selected"></option>
    <option value="1" selected="selected">Food</option>
    <option value="2" selected="selected">Toys</option>
    <option value="3" selected="selected">Books</option>
</select>

<select id="ProductList"></select>

<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
    function CategoryList_OnChange() {
        var selected = $('#CategoryList').val();
        if (selected != null && selected != '') {
            $.getJSON('SelectList/ProductList/' + selected, function(selectList) {
                $('#ProductList option').remove();
                $.each(selectList, function(index, value) {
                    $('#ProductList').append("<option value='" + value.Value + "'>" + value.Text + "</option>");
                });
            });
        }        
    }
</script>

Is there any way to keep the ProductList populated even when navigating away from the page? My understanding of how browsers work is that they are meant to keep state of the page, even when navigating away.

I know that I could merely put code in

$(document).ready(function() { ... });

which will explicitly call the onchange method but this has the disadvantage of making a call to the website when in fact I want the page to maintain the EXISTING state.

Please Help!

Was it helpful?

Solution

Why should a browser keep the state that resulted from js manipulation. Most browsers won't.

You could try using the cookies library and save what (if any) Category was selected. When the user later returns to the page and hasn't cleared the cookies in the meantime you can read the value out from the cookie and automatically issue the $.getJSON request to "refill" the product list

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