开发者

Swap default selected select options with pure Javascript

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开发者_JAVA技巧. So im trying to learn it.


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;


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜