[javascript] How to set default value for HTML select?

I have a HTML select like this:

<select>
    <option>a</option>
    <option>b</option>
    <option>c</option>
</select>

and I have a variable named temp in my JavaScript:

var temp = "a";

Now I want to set the value of the option that is equal to temp as default value for my select.

How can I do it?

This question is related to javascript html

The answer is


Simplay you can place HTML select attribute to option a like shown below

Define the attributes like selected="selected"

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

You could use...

<option <?= ($temp == $value) ? "SELECTED" : "" ?> >$value</opton>

Edit: I thought I was looking at PHP questions... Sorry.


You should define the attributes of option like selected="selected"

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

You first need to add values to your select options and for easy targetting give the select itself an id.

Let's make option b the default:

<select id="mySelect">
    <option>a</option>
    <option selected="selected">b</option>
    <option>c</option>
</select>

Now you can change the default selected value with JavaScript like this:

<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}
</script>

See it in action on codepen.


you can define attribute selected="selected" in Ex a