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.
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>
You can change options easily with JavaScript. I would advise to use an additional library to ease DOM manipulation, such as JQuery. An example code would look like the example below. You have to make sure to define an event on which the options should be changed. The example listens to changes within the input field.
<input type="text" id="food" value="vegetables"/>
<select id="pickone"></select>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script>
var fruits = ["Apple", "Oranges", "Bananas"];
var vegetables = ["Eggplants", "Olives"];
vegetables.forEach(function(item){
$('#pickone').append("<option>" + item + "</option>");
});
$('body').on('keyup', '#food', function (){
if ($('#food').val() === 'fruits') {
$('#pickone').html("");
fruits.forEach(function(item){
$('#pickone').append("<option>" + item + "</option>");
});
}
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With