更改< select> javascript的动态选项 [英] Change <select> options with javascript dynamically
本文介绍了更改< select> javascript的动态选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用javascript if/else函数来更改表单的选择选项吗?我不想使用CSS隐藏/显示不同的下拉菜单,所以这里是我要介绍的内容:
Can I use a javascript if/else function to change the select options of a form? I don't want to use CSS to hide/display different dropdown menus, so here is what I've ccome up with:
function getType() {
var x = document.getElementById("food").value;
var items;
if (x === "fruit") {
items = "Apple" || items = "Oranges" || items = "Bananas";
else {
items = "Eggplants" || items = "Olives"
}
document.getElementById("pickone").value;
}
<input type="text" id="food">
<select id="pickone">
<option id="1"></option>
<option id="2"></option>
</select>
我似乎找不到有关如何执行此操作的任何文档,因此任何帮助都将非常有用.
I can't seem to find any documentation about how to do this, so any help would be great.
推荐答案
您可以为options
附加字符串,然后将其设置为选择字段的innerHTML
:
You could append a string for the options
and set it as innerHTML
of your select field afterwards:
function getType() {
var x = document.getElementById("food").value;
var items;
if (x === "fruit") {
items = ["Apple", "Oranges", "Bananas"];
} else {
items = ["Eggplants", "Olives"]
}
var str = ""
for (var item of items) {
str += "<option>" + item + "</option>"
}
document.getElementById("pickone").innerHTML = str;
}
document.getElementById("btn").addEventListener("click", getType)
<input type="text" id="food">
<button id="btn">click</button>
<select id="pickone">
</select>
这篇关于更改< select> javascript的动态选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文