I have two spans that appear or hide when their respective option is selected from a select-menu. By default, both spans are set to display: none in CSS. I would like to maintain the visibility of any currently visible span after the page reloads (in case there was a validation error, for example).
I did this with a checkbox and it was easy, but I can’t figure it out with a select-menu.
// Toggles the div based on selected option
$(function() {
$('#maintenanceIntervalId').change(function() {
var value = $('#maintenanceIntervalId option:selected').val()
switch(value) {
case "2": {
$("#weekly-maintenance-on").show();
$("#monthly-maintenance-on").hide();
break;
}
case "3": {
$("#monthly-maintenance-on").show();
$("#weekly-maintenance-on").hide();
break;
}
case "1": {
$("#weekly-maintenance-on").hide();
$("#monthly-maintenance-on").hide();
break;
}
}
});
});
The above works as expected. But in order to get the currently visible span to stay visible after page reload, I moved the switch statement into its own function toggleMaintenanceDiv() and added the following line:
toggleMaintenanceDiv($('#maintenanceIntervalId option:selected'))
This does not work, however.
HTML:
<select id="maintenanceIntervalId">
<option value="1">Day</option>
<option value="2">Week</option>
<option value="3">Month</option>
</select>
<span id="weekly-maintenance-on">Stuff one</span>
<span id="monthly-maintenance-on">Stuff two</span>
The script is reloaded each time with page loading, all variables or states of javascript will be lost after reloading. I think you can store the visible span IDs in cookie and when the page loads each time, it checks the cookie first and sets corresponding spans visible.