[英]When an option selected I wanna change the other select tags options
在我的 Django 模板中,我有兩個 select 標簽。 我想將第二個標簽更改為鏈接到第一個標簽。 例如,在第一個標簽動物選項 select 中,我想在第二個 select 標簽上顯示動物。 當第一個標簽中的植物 select 我想在第二個 select 標簽中顯示植物。 我怎樣才能做到這一點?
(animals or plants)
<select id="creatures">
{% for x in list %}
<option value="{{x.creature}}">{{x.creature}}</option>
{% endfor %}
</select>
<select id="instances">
{% for y in instances %}
<option value="{{y.instance}}">{{x.instance}}</option>
{% endfor %}
</select>
有多種方法。
這是您可以采用的一種方法:
document.getElementById("first").addEventListener("change", (e) => {
const selectedOption = e.target.value;
// update second select based on what is selected
document.getElementById("second").innerHTML = getSecondSelectOptions(
selectedOption
);
});
function getSecondSelectOptions(category) {
const animals = ["cat", "dog", "bird"];
const plants = ["lily", "lotus"];
if (category === "animals")
return animals
.map((value) => `<option value="${value}">${value}</option>`)
.join("");
else if (category === "plants")
return plants
.map((value) => `<option value="${value}">${value}</option>`)
.join("");
else return ""; // clear second select
}
我們正在使用innerHTML
更新第二個 select 的內容。
另一種方法是靜態編寫不同的 select 元素,但默認隱藏。 然后你可以根據第一個select中選擇的選項取消隱藏你想要的select元素。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.