[英]Populating a drop down with a array of values passed from JavaScript
I have a Drop down which shows continents.我有一个显示大陆的下拉菜单。 Based on the selection of continent the next Drop down will show the relevant countries of that continent.This is how I did it根据大洲的选择,下一个下拉列表将显示该大洲的相关国家。我就是这样做的
<label for="website">Continent</label>
<Select class="form-control" th:field="*{continent}" id="continent">
<option th:value="Africa" th:text="Africa"></option>
<option th:value="Europe" th:text="Europe"></option>
<option th:value="Asia" th:text="Asia"></option>
</Select>
<label for="website">Country</label>
<Select class="form-control" th:field="*{country}" id="country"> </Select>
Here is the JavaScript Code I used to do that这是我用来做的 JavaScript 代码
<script>
var select = document.getElementById('continent');
select.addEventListener("change",function() {
passValue(this.value);
});
function passValue(x) {
var a = x;
if (a=='Asia'){
var options=['China','India','Pakistan','Malaysia']
}else if (a == 'Europe'){
var options=['UK','Switzerland','Germany','France']
}else if(a=='Africa'){
var options=['South Africa','Ethiopia','Kenya','Moroco']
}
var select = document.getElementById("country");
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 I select a continent for an example Europe, the countries in Europe are shown on the second Drop down as I expected.如果我选择一个大陆作为示例欧洲,那么欧洲的国家会按我的预期显示在第二个下拉列表中。 But if I select another continent for a example Asia, then all the countries in previous selection and current selection (countries in Europe and Asia) are shown on the second Drop down但是如果我选择另一个大陆作为示例亚洲,那么之前选择和当前选择中的所有国家(欧洲和亚洲的国家)都会显示在第二个下拉列表中
After Selecting Europe on Drop down 1在下拉列表 1 上选择欧洲后
Selecting Asia on Drop down 1 after selecting Europe选择欧洲后在下拉列表 1 上选择亚洲
Please give a solution for this issue.请给出这个问题的解决方案。
You could set first the options in dropdown to empty before you append again those new options, like this one您可以先将下拉列表中的选项设置为空,然后再添加这些新选项,例如这个
if you use Jquery:如果您使用 Jquery:
$('#country').empty()
if you use pure JS如果你使用纯 JS
document.getElementById("country").innerHTML ="";
You need to clear your options variable on subsequent clicks so it won't keep adding onto what's already there.您需要在随后的点击中清除您的选项变量,这样它就不会继续添加到已经存在的内容上。 This should do the trick.这应该可以解决问题。
function passValue(x) {
var options = []; <--- Set the options array to empty
var a = x;
if (a=='Asia'){
options=['China','India','Pakistan','Malaysia']
}else if (a == 'Europe'){
options=['UK','Switzerland','Germany','France']
}else if(a=='Africa'){
options=['South Africa','Ethiopia','Kenya','Moroco']
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.