Sharlike
Sharlike

Reputation: 1789

Compensate for back button leaving select element unpopulated

I have a form with two select elements, where I bind an onchange event on the parent select which uses ajax to populate options for the child select. I bind the event with jQuery, but use an onchange attribute in the below example for simplicity.

<select id="parent_select" onchange="getOptions($(this).val(),'child_select');">
    <option>A</option>
    <option>B</option>
    ...
</select>
<select id="child_select"></select>

Submitting the form takes the user to a new page. If they go back using the browser's back button, the parent select will still have the selected option (at least in chrome). However, the child select won't be populated, which is expected.

What is the best way to account for this scenario and populate the child options?

So far, I have come up with checking if the parent has a selected option in $(document).on('ready',function(){...});. Is there a superior approach?

Upvotes: 1

Views: 225

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

You can use a URL hash to record and restore page state.

See: Working with single page websites and maintaining state using a URL hash and jQuery

The main example show you how to use the hash. You need to record which element is selected with like #S1=3, then look for that value when the page loads, and set the index of your SELECT accordingly.

Upvotes: 2

Related Questions