Change <select> options with javascript dynamically
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>
Your logic is not very right, specially where you try to do this items = "Apple" || items = "Oranges" || items = "Bananas";
with the above statement you are saying that itens
are Apple OR Oranges OR Bananas, only one at once...
you'll need an array of elements, like this: var itens = ["Apple", "Oranges", "Bananas"];
Then, you will need to loop through it to add them to the select, like this:
var itens = ["Apple", "Orange", "Banana"];
var selectElem = document.getElementById("mySelect");
for (var i = 0; i < itens.length; i++){
var item = itens[i];
var element = document.createElement("option");
element.innerText = item;
selectElem.append(element);
}
<select id="mySelect"></select>
With that, now you can achieve what you want, just follow this logic...
you can also, if you want, add an `if` statement to check what is the input value, then set the options based on the input value, as you are already trying to do.