Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selected option of select element by its ID?

<select id="comboBox">
    <option id="1">One</option>
    <option id="2">Two</option>
    <option id="3">Three</option>
    <option id="4">Four</option>
</select>

I want to select option with ID 3. Is there any way how to do it without loop? I expect something like this

$("#comboBox").val("3");

but with ID instead of value. (So I mean to access that option as member of comboBox, not through selector like document.getElementById('3');)

like image 833
juice Avatar asked Apr 22 '14 11:04

juice


1 Answers

<script type="text/javascript">
    document.getElementById("3").selected=true;
</script>

or

<script type="text/javascript">
    document.getElementById("comboBox").options[2].selected=true;
</script>

or

<script type="text/javascript">
    document.getElementById("comboBox").selectedIndex=2;
</script>

or

<script type="text/javascript">
    document.getElementById("comboBox").options.namedItem("3").selected=true;
</script>

For the last one see https://developer.mozilla.org/en/docs/Web/API/HTMLSelectElement#namedItem() and http://www.w3schools.com/jsref/coll_select_options.asp

You could skip the reference to options for the shorter document.getElementById("comboBox").namedItem("3").selected=true;

like image 129
Zlatin Zlatev Avatar answered Oct 23 '22 06:10

Zlatin Zlatev