Notorious
Notorious

Reputation: 3217

Preserve dynamically changed select values when back button clicked

I have a form which filters through different cars, and it's working perfect.

When a user selects a "Make" the correct sibling "Models" are populated into the next dropdown, so on and so forth.

The problem is that once a user has performed a search, if they click the browser's back button, the select values which are dynamically populated - are back to default!

I am not using ajax to dynamically populate the select fields, but only javascript where I am reading a JSON file and updating the models/series/etc like that.

I have looked at this post: Preserve dynamically changed HTML on back button

And I do not understand how this works, I have also heard about localstorage - what would be the best avenue for me to travel down? Thanks.

Upvotes: 1

Views: 7002

Answers (2)

ajbeaven
ajbeaven

Reputation: 9582

Using localStorage for this can be a bit unwieldy (when and how should I clear this value?) and there are security related considerations that may make it an infeasible solution.

Another option is to use a hidden textbox which makes use of the browser's default behaviour.

When a page is loaded after clicking the back button, browsers appear to populate textboxes based on the value contained in it when the user left the page (even if that value was dynamically changed). Note, this is different to how hidden inputs are handled, where dynamic changes are ignored, so you must use a textbox.

<select></select>
<input type="text" style="display:none" />

<script>
  // store the dropdown's value in a hidden textbox which is persisted and 
  // used to populate the dropdown when the back button is used to get here
  $('select').on('change', function() {
    $('input').val($(this).val());
  });

  // example showing dynamic population of dropdown
  $.ajax({
    url: 'api/get-dropdown-options',
    success: function(data) {
      // dynamically populate the dropdown
      $('select').html(data);

      // update the dropdown's value based on the persistent value
      // retained in the hidden textbox
      $('select').val($('input').val());
    }
  });
</script>

Upvotes: 2

Reza Karami
Reza Karami

Reputation: 515

Because the data is dynamically loaded, the browser will not be able to repopulate the previously selected entries when the user goes back to the previous page.

I suggest you make use of the browser's localStorage to store the latest selections and retrieve them when the user goes back. To accomplish that it's as simple as setting a new variable to the localStorage object and later retrieving it like so:

localStorage.make = "BMW";

alert(localStorage.make);

Also here's a more useful example:

select = document.getElementById("make");

if (localStorage.make) {
    select.options[localStorage.make].selected = true;
}

Upvotes: 1

Related Questions