-1

I have to choose an option from a html file:

<select id="color">
    <option>red</option>
    <option>yellow</option>
    <option>green</option>
    <option>orange</option>
</select>

for example i want to select green. I have already tried:

var color = "green"
document.getElementById("color").options.value = color;
document.getElementById("color").value = color;

but they don't work. (option tag must be withouth name, id, ...)

IlTvrco
  • 23
  • 5
  • 1
    Does this answer your question? [How do I programmatically set the value of a select box element using JavaScript?](https://stackoverflow.com/questions/78932/how-do-i-programmatically-set-the-value-of-a-select-box-element-using-javascript) – KetZoomer Mar 31 '21 at 21:37
  • You say that option tag must be without name, id, ... . Does this also include *value*? Because if you were to add `value="colorname"` to your option tags, you should be able to set it through `document.getElementById("color").value = color;` – Alain Doe Mar 31 '21 at 21:43

1 Answers1

0

Change your HTML to this;

<select id="color">
    <option value="red">red</option>
    <option value="yellow">yellow</option>
    <option value="green">green</option>
    <option value="orange">orange</option>
</select>

Then the following JavaScript should work;

var color = "green"
document.getElementById("color").value = color;

A snippet as an example;

var color = "green"
document.getElementById("color").value = color;
console.log( document.getElementById("color").value );
<select id="color">
    <option value="red">red</option>
    <option value="yellow">yellow</option>
    <option value="green">green</option>
    <option value="orange">orange</option>
</select>

If adding value attributes isn't a possibility for whatever reason, you'll end up having to loop over the option tags and selecting them through that.

function selectColor( color )
{
  var select = document.getElementById("color");
  for ( var i=0; i<select.childNodes.length; i++ ) {
    if ( select.childNodes[i].textContent === color ) {
      select.childNodes[i].selected = true;
      return true;
    }
  }
  return false;
}
selectColor("green");
console.log( document.getElementById("color").value );
<select id="color">
    <option>red</option>
    <option>yellow</option>
    <option>green</option>
    <option>orange</option>
</select>
Alain Doe
  • 532
  • 3
  • 7