我试图显示第二个下拉菜单,这取决于对第一个下拉菜单的选择的反应/选择。我想显示第二个下拉菜单,具体取决于第一个下拉菜单的选择。
我尝试使用if语句,但是那些语句并没有帮助我前进。
<select id="countries">
<option id="US" value="unitedStates" > United States </option>
<option id="CA" value="canada" > Canada </option>
</select>
<script type="text/javascript">
//Global variable for the Countries drop down menu
var country = document.getElementById('countries');
</script>
我想显示第二个下拉菜单,其中列出了美国或加拿大的城市列表,具体取决于选择的城市。
答案 0 :(得分:2)
尝试以下代码:
json:"data,omitempty" protobuf:"bytes,2,rep,name=data"
var cities = {
unitedStates: ["New York", "Washington"],
canada: ["Toronto", "Ottawa"]
}
var country = document.getElementById('countries');
var city = document.getElementById('cities');
country.onchange = () => {
let v = cities[country.value];
city.innerHTML = v ? v.map(c => `<option id="${c}" value="${c}">${c}</option>`) : '';
}
这里,我们根据第一<select id="countries">
<option></option>
<option id="US" value="unitedStates" > United States </option>
<option id="CA" value="canada" > Canada </option>
</select>
<select id="cities"></select>
中的选择来更改第二<input>
中的每个选项。数据来自<input>
对象。
UPD:如果在第一个组合中不需要空值
cities
var cities = {
"United States": ["New York", "Washington"],
"Canada": ["Toronto", "Ottawa"]
}
var districts = {
"New York": ["District 1", "District 2"],
"Washington": ["District 3", "District 4"],
"Toronto": ["District 5", "District 6"],
"Ottawa": ["District 7", "District 8"]
}
let option = d => `<option id="${d}" value="${d}">${d}</option>`;
var country = document.getElementById('countries');
var city = document.getElementById('cities');
var district = document.getElementById('districts');
country.innerHTML = Object.keys(cities).map(option);
linkComboBoxes(country, city, cities);
linkComboBoxes(city, district, districts);
function linkComboBoxes(input1, input2, data) {
input1.onchange = () => {
input2.innerHTML = data[input1.value].map(option);
input2.onchange && input2.onchange();
}
input1.onchange();
}