Ответ 1
Вот рабочий пример желаемой функциональности. Я использую localStorage, как человек, который ответил передо мной.
https://jsfiddle.net/a0uj5d86/2/
//handle select changes, put new data in storage
document.getElementById('country').onchange = function () {
console.log('country change');
localStorage.setItem('country', this.value);
populateStates('country', 'state');
};
document.getElementById('state').onchange = function () {
localStorage.setItem('state', this.value);
};
document.getElementById('country2').onchange = function () {
localStorage.setItem('country2', this.value);
};
Тогда в населенных странах в конце у меня есть маленький дидд, который идет
var selection = 'USA';
if (localStorage.getItem(countryElementId)) {
console.log('found ' + countryElementId + ' in storage = ' + localStorage.getItem(countryElementId));
var selection = localStorage.getItem(countryElementId);
}
//select our country (default USA, or local storage if applicable)
findAndSelect(countryElementId, selection);
if (countryElementId == 'country') {
//we just populated country, now populate states
populateStates(countryElementId, stateElementId);
if (localStorage.getItem(stateElementId)) {
//if weve got a state to select, select it
findAndSelect(stateElementId, localStorage.getItem(stateElementId));
} else {
findAndSelect(stateElementId, 'Alabama');
}
}
Я также сделал несколько вариантов рефакторинга для кода, который у вас был. Дайте ему взглянуть и вернитесь ко мне с любыми вопросами!