I use materialize, and the problem is: I have 2 select-div with options, and when I choose Ukraine in the first select? The second select would show me only Lviv, Odessa, Kiev, kharkiv. If I choose Poland in the first select, the second select would show me only Warsaw and Krakow.
I've already asked the same question, and received few answers which was useful, but when I linked materialize CSS, code doesn't work.
<div class="input-field col s12">
<select id="country-list" onchange="changeCountry(this)">
<option value="none" disabled selected>Choose your option</option>
<option value="1">Ukraine </option>
<option value="2">Poland</option>
</select>
</div>
<div class="input-field col s12">
<select id="city-list">
<option value="none" disabled selected>Choose your option</option>
<option value="1">Lviv</option>
<option value="1">Kiev</option>
<option value="1">Kharkiv</option>
<option value="1">Odessa</option>
<option value="2">Krakow</option>
<option value="2">Warsaw</option>
</select>
</div>
And here JavaScript
var countryObject = {
Ukraine: ["Lviv", "Kiev", "Kharkiv", "Odessa"],
Poland: ["Krakow", "Warsaw"],
};
function changeCountry() {
document.getElementById("city-list").options.length = 0;
var cityListArray =
countryObject[document.getElementById("country-list").value];
console.log(document.getElementById("city-list").options);
for (var item = 0; item < cityListArray.length; item++) {
document.getElementById("city-list").options[
document.getElementById("city-list").options.length
] = new Option(cityListArray[item], cityListArray[item]);
}
}
There is no need to continuously find the elements on the page. Find them once, and use the resulting element later when needed.
const countryObject = {
Ukraine: ["Lviv", "Kiev", "Kharkiv", "Odessa"],
Poland: ["Krakow", "Warsaw"],
};
const countryListEl = document.getElementById("country-list");
const cityListEl = document.getElementById("city-list");
const defaultOption = new Option("Choose your option");
defaultOption.disabled = true;
defaultOption.selected = true;
function changeCountry() {
cityListEl.options.length = 0;
cityListEl.options[0] = defaultOption;
const cityListArray = countryObject[countryListEl.value];
for (let i = 0; i < cityListArray.length; i++) {
cityListEl.options[i + 1] = new Option(
cityListArray[i],
cityListArray[i]
);
}
}
<div class="input-field col s12">
<select id="country-list" onchange="changeCountry(this)">
<option value="none" disabled selected>Choose your option</option>
<option value="Ukraine">Ukraine </option>
<option value="Poland">Poland</option>
</select>
</div>
<div class="input-field col s12">
<select id="city-list">
<option value="none" disabled selected>Choose your option</option>
</select>
</div>