select is blank when giving history.back ()

1

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

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

Code sample.

$(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><selectname='estado'id='estado'><optionvalue="MG">MG</option>
<option value="SP">SP</option>
</select>
<select name='cidade' id='cidade'>
</select>
    
asked by anonymous 05.05.2017 / 21:42

1 answer

0

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

A quick search on the original OS reveals a gambiarra that can be used to force the reexecution of Javascript in Firefox . By the comments that go until last year, this "solution" still seems to work.

window.onunload = function(){}; 

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

Now, if you really need to take the user to a page that he has already passed, and want to use the go back feature to save time / processing, I can suggest you try two alternatives:

  • open the page from which you would return in another tab / window to preserve the page you want to go back to, or ...;
  • Redirect to the target page, and if there is something for which processing is heavy, keep that something in the user session, cached, or if you are working with ASP.NET MVC on the TempData object (which is done for hold data that should have a very short lifetime).
05.05.2017 / 21:51