javascript change select option code example

Example 1: javascript select change selected

const options = Array.from(select.options);
options.forEach((option, i) => {
  if (option.value === use_id) select.selectedIndex = i;
});

Example 2: javascript change select options dynamically

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);

Tags:

Html Example