2

Here i have read how to set a form option selected by index

<select name="sel"> 
  <option value="o1">option1</option>
  <option value="o2">option2</option>
</select>

document.getElementsByName('sel')[0].selectedIndex = 0; or
document.getElementsByName('sel')[0].selectedIndex = 1;

but is it possible to set an option selected by referencing an option value instead of index?

Community
  • 1
  • 1
Viktor
  • 623
  • 4
  • 10
  • 25

1 Answers1

7

You could just set the value property of the <select> element, as answered in How do I programatically set the value of a select box element using javascript?

<select name="sel"> 
    <option value="o1">option1</option>
    <option value="o2">option2</option>
</select>

<select name="sel"> 
    <option value="o1">option1</option>
    <option value="o2">option2</option>
</select>

document.getElementsByName("sel")[0].value="o2";

JSFiddle

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161
  • That's right. If you just `alert` or `console.log` the statement, you'll see it returns the value (`o2` in this case). Also, take into account the `selected` attribute is to be applied to the ` – Xavi López Feb 28 '13 at 16:15
  • ^^this is just the same as .selectedIndex=1; isn't it? – Viktor Feb 28 '13 at 16:16
  • Indeed. You can set the selected option by index with the `selectedIndex` property or by value with the `value` property. – Xavi López Feb 28 '13 at 16:21
  • aahhhhh! ok! I get it! Thank you very very very very very much! – Viktor Feb 28 '13 at 16:27
  • sorry, can't vote up your answer because i do not have enough reputation points... – Viktor Feb 28 '13 at 20:51