How to cache data from <select> ?
How to save value from select to cache and display them on another page?
How to cache data from <select> ?
How to save value from select to cache and display them on another page?
You do not need a cache, but cookies ... SetCookie to set values in the browser's memory. GetCookie to get values from memory. https://learn.javascript.ru/cookie The article describes the installation and reading of cookies
// возвращает cookie с именем name, если есть, если нет, то undefined function getCookie(name) { var matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "= ([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; } document.cookie = "userName=Vasya"; getCookie("userName") SetCookie and GetCookie - GrundyAlternatively, you can also use localStorage . When selecting an item in a list, write the key to it, with the value of the selected item. Then, in any necessary place to check the presence of this key, and if it is, then set the value of the active element of the list.
// Выбираем на странице нужный select var mySelect = document.getElementById('mySelct'); // При событии "изменения" нашего списка (выборе элемента) выполняем функцию mySelect.onchange = function () { // Берём значение выбранного элемента списка item = this.options[this.selectedIndex].value; // Выводим в консоль console.log('Выбран', item); // Записываем в localStorage значение выбранного элемента списка localStorage.setItem('activeSelect', item); } /* ... А где надо проверяем, есть ли в localStorage ключ activeSelect. Если он есть, то значит ранее был выбран элемент списка. Значением этого ключа является value выбранного ранее элемента списка. */ var activeSelect = localStorage.getItem('activeSelect'); // Проверяем есть ли такой ключ if(activeSelect) { // Выводим в консоль console.log('Есть в localStorage', activeSelect); // "Активным" элементом делаем тот, к которого значение, как то, // что мы сохранили в activeSelect ранее ) mySelect.value = activeSelect; } <select id="mySelct"> <option value="1">Раз</option> <option value="2">Два</option> <option value="3">Три</option> </select> And of course, when you no longer need to store this key, you should delete it:
localStorage.removeItem('activeSelect'); select - var mySelect = document.getElementById('mySelct'); . The fragment in response that starts with the var activeSelect ... is exactly the same and is responsible for checking for the presence of a key. Although I have a suspicion that it is better to do this kind of thing on the server side, but if it is required on the client, this should work. - Alexander IgorevichmySelect to hang the onchange event, and the value of the selected list item is stored in activeSelect . In the answer I wrote in more detail comments for clarity. - Alexander IgorevichSource: https://ru.stackoverflow.com/questions/697139/
All Articles