У меня есть три выпадающих списка:
I try to write the options' values to the local storage to keep the selected values after refreshing the page.
function populateStorage() {
localStorage.setItem('university', document.getElementById('university').value);
localStorage.setItem('faculty', document.getElementById('faculty').value);
localStorage.setItem('department', document.getElementById('department').value);
getUpdatedStorage()
}
function getUpdatedStorage() {
document.getElementById('university').value = localStorage.getItem('university');
document.getElementById('faculty').value = localStorage.getItem('faculty');
document.getElementById('department').value = localStorage.getItem('department');
}
if(!localStorage.getItem('university')) {
populateStorage();
} else {
getUpdatedStorage();
}
Here's the code running at each сhange event:
$('#university').change(function() {
let universityId = $(this).val();
$('#faculty').find('option').not(':first').remove();
$.ajax({
url: 'exam_sheet/faculty/' + universityId,
type: 'get',
dataType: 'json',
success: function(response) {
if(response['data'] !== null) {
for(let i = 0; i < response['data'].length; i++) {
let facultyId = response['data'][i].subd_id;
let facultyName = response['data'][i].subd_short_name;
let option = `${facultyName}`;
$('#faculty').append(option);
populateStorage();
}
} else {
return false;
}
}
});
});
$('#faculty').change(function() {
let facultyId = $(this).val();
$('#department').find('option').not(':first').remove();
$.ajax({
url: 'exam_sheet/department/' + facultyId,
type: 'get',
dataType: 'json',
success: function(response) {
if(response['data'] !== null) {
for(let i = 0; i < response['data'].length; i++) {
let departmentId = response['data'][i].subd_id;
let departmentName = response['data'][i].subd_name;
let option = `${departmentName}`;
$('#department').append(option);
populateStorage();
}
} else {
return false;
}
}
});
$('#department').change(function() {
let departmentId = $(this).val();
$.ajax({
url: 'exam_sheet/group/' + departmentId,
type: 'get',
dataType: 'json',
cache: true,
success: function(response) {
if(response['data'] !== null) {
for(let i = 0; i < response['data'].length; i++) {
let groupId = response['data'][i].stg_id;
let groupName = response['data'][i].stg_name;
let option = `${groupName}`;
$('#group').append(option);
populateStorage();
}
} else {
return false;
}
}
});
As you can see, the values are saved in the local storage.
But after refreshing the page the values aren't displayed as expected and look the following:
введите описание изображения здесь
Я новичок в использовании локального хранилища и хочу знать, как решить эту проблему.