How input visible from select value when returning from another page

Viewed 30

When selecting 1_preduzece, the input field my_field is displayed, however, when data is entered into this input and the user switches to another html page, in case he returns to the page this input field disappears but 1_preduzece remains selected. How to keep this input visible when returning from another page if 1_preduzece is selected.

<select required="" aria-required="true" name="svojina" id="svojina" onchange="showMessage(); showDiv(this)">
  <option value="" disabled selected>Odaberi:</option>
  <option value="1_preduzece">Korisnik 1</option>
  <option value="2_preduzece">Korisnik 2</option>
</select>

<p id="vrsta"></p>

<script>
function showMessage() {
    var x = document.getElementById("svojina").value;
    document.getElementById("vrsta").innerHTML = "";

    if (x == "1_preduzece") {
        document.getElementById("vrsta").innerHTML = "";
    }

    if (x == "2_preduzece") {
        document.getElementById("vrsta").innerHTML = "";    
    }
}
</script>


<div id="hidden_div" style="display: none;">

<input id="my_field" type="text" name="my" maxlength="5" size="30" disabled="true" onkeyup="saveValue(this);">
</div>


<script>
  // input to track
  let field = document.getElementById("my_field"); 
  if (sessionStorage.getItem("autosave")) {
    // Restore a content of the input
    field.value = sessionStorage.getItem("autosave");
  }
 
  // Listen for changes in the input field
  field.addEventListener("change", function() {
    // save value into sessionStorage object 
    sessionStorage.setItem("autosave", field.value);
  });
</script>


<script type="text/javascript">
function showDiv(select){
   if(select.value=="1_preduzece"){
    document.getElementById('hidden_div').style.display = "block";
    document.getElementById('my_field').disabled = false;

   } else {
    document.getElementById('hidden_div').style.display = "none";
    document.getElementById('my_field').disabled = true;
   }
} 
</script>
1 Answers

What you're seeing is a browser cache of sorts. The best way to circumvent that is to run a javascript function on page init to reset your form values.

In vanilla JS:

window.addEventListener('DOMContentLoaded', () => {
   document.querySelector('select[name=svojina]').value='';
})

In JQuery

$(function() {
   $('select[name=svojina]').val('');
})
Related