juice
juice

Reputation: 587

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');)

Upvotes: 17

Views: 54141

Answers (5)

KooiInc
KooiInc

Reputation: 123006

Use document.querySelector to retrieve an option, then use either setAttribute to set the selected state or set the selected state directly.

const getOptionById = id => 
  document.querySelector(`#comboBox > option[id="${id}"]`);

// direct set
getOptionById(3).selected = true;

// setAttribute
setTimeout(() => getOptionById(4).setAttribute(`selected`, true), 3000);
<select id="comboBox">
    <option id="1">One</option>
    <option id="2">Two</option>
    <option id="3">Three</option>
    <option id="4">Four</option>
</select>

Upvotes: 5

Zlatin Zlatev
Zlatin Zlatev

Reputation: 3098

<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;

Upvotes: 22

Manwal
Manwal

Reputation: 23836

selectedIndex is a property of HTMLSelectElement, you can get its index using the index property, so you can do the following:

document.getElementById("comboBox").selectedIndex = document.getElementById('3').index;

Updated: Demo

Updating option on Button Click event: New Demo

Updating option on Button Click event in decreasing order: Another Demo

Upvotes: 0

Shijin TR
Shijin TR

Reputation: 7788

You can try this,if your id is in the same order

document.getElementById("comboBox").selectedIndex = 2;

Demo

Upvotes: 0

Martin Zugnoni
Martin Zugnoni

Reputation: 1439

This worked for me:

$("#2").attr({"selected": true});

Note I'm using JQuery selector and .attr function.

Upvotes: 0

Related Questions