select goes blank when giving history.back()

Asked

Viewed 36 times

1

I set up a system where I inform the state and jQuery loads the cities.

The problem is that when I run a history.back() and back to the form page select city goes blank. How do I make it not lose value?

Code example.

$(document).ready(function() {
  $("#estado").on("change", function() {
    if ($(this).val()) {
      $.getJSON('Cidades.php?search=', {
        estado: $(this).val(),
        ajax: 'true'
      }, function(j) {

        // Carrega as cidades
        var options = null;
        for (var i = 0; i < j.length; i++) {
          options += '<option value="' + j[i].id + '">' + j[i].nome + '</option>';
        }

        // Adiciona cidades
        $('#cidade').html(options).show().blur();
      });
    } else {

      // Remove cidades
      $('#cidade').html('<option value=""></option>').blur();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name='estado' id='estado'>
<option value="MG">MG</option>
<option value="SP">SP</option>
</select>
<select name='cidade' id='cidade'>
</select>

1 answer

0

The problem is that when you use the back functionality, the behavior of the page assembly is in charge of the browser - and I believe that in your case, the browser only reloads the HTML it had in memory, without necessarily running Javascript again.

A quick search of the original OS reveals a gambiarra that can be used to force Javascript to re-enter Firefox. From the comments, which go up to last year, this "solution" seems to still work.

window.onunload = function(){}; 

I believe it should work on Opera and Chrome. I suggest testing in each browser.

Now, if you really need to take the user to a page they’ve already passed, and want to use the go-back feature to save time/processing, I might suggest you try two alternatives:

  • open the page from which you would return in another tab/window to preserve the page to which you want to return, or...;
  • redirect to the target page, and if there is something to which the processing is heavy, keep this something in the user session, cached, or if you are working with ASP.NET MVC, in the Tempdata object (which is made to hold data that must have a very short lifespan).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.