tags:

views:

194

answers:

2

I have a select box as follows

<select>
<option value="yes">Yes</option>
<option value="No" selected="selected">No</option>
<option value="Maybe">Maybe</option>
<option value="So">So</option>
</select>

I would like

<select>
<option value="yes">Yes</option>
<option value="No">No</option>
<option value="Maybe" selected="selected">Maybe</option>
<option value="So">So</option>
</select>

*note default selection is now "Maybe" instead of "No"

I learned jquery before really getting comfortable with pure JavaScript. So im trying to learn it.

+2  A: 

I would assign an id to the select element:

<select id="choices">
    <option value="yes">Yes</option>
    <option value="No" selected="selected">No</option>
    <option value="Maybe">Maybe</option>
    <option value="So">So</option>
</select>

Then, access the options via the standard options array on <select> elements:

var choices = document.getElementById('choices');
choices.options[2].selected = true;
Triptych
choices.selectedIndex = 2 would be good as well :)
David Hedlund
@David Yup. Haven't done this manually in years.
Triptych
+1  A: 

You should assign an id to the select element then do this:

var s = document.getElementById( 'select_box' );
s.options[ 2 ].selected = true;
Jacob Relkin