我有2个下拉菜单,这是用户选择BMW我要填充数据1,2,3,4,5的数据,而当他选择沃尔沃时我要显示5,6,7,8,9的数据。数据在第二个下拉列表中得到填充,但是我也可以看到旧数据,而且我单击列表的次数越来越多。我只想显示有关选择的特定数据,并且数据也不应重复。下面是我的方法。
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("mySelect").value;
if(x=='BMW'){
var select = document.getElementById("participant");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
if(x=='Volvo'){
var select = document.getElementById("participant");
var options = ["6", "7", "8", "9", "10"];
console.log(options)
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
}
</script>
</head>
<body>
<select id="mySelect" onchange="myFunction()">
<option value="" disabled selected>Select Type</option>
<option value="BMW">BMW</option>
<option value="Volvo">Volvo</option>
</select>
<br><br>
<select id="participant">
<option>select</option>
</select>
</body>
</html>
答案 0 :(得分:1)
在添加新的innerHTML
之前,您应该更改<select>
的{{1}}。
<option>
function myFunction() {
var x = document.getElementById("mySelect").value;
var select = document.getElementById("participant");
//this line clears the old data.
select.innerHTML = '<option>Select</option>'
if(x=='BMW'){
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
if(x=='Volvo'){
var options = ["6", "7", "8", "9", "10"];
console.log(options)
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
}