Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 231
Saman Avatar asked Oct 26 '13 20:10

Saman


People also ask

How do I set the default selection in HTML?

The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option.

How do I change selection options in HTML?

We can change the HTML select element's selected option with JavaScript by setting the value property of the select element object. We have a select drop down with some options and 2 buttons that sets the selected options when clicked. We get the 2 buttons with getElementById .

How do you select in JavaScript?

To select a <select> element, you use the DOM API like getElementById() or querySelector() . How it works: First, select the <button> and <select> elements using the querySelector() method. Then, attach a click event listener to the button and show the selected index using the alert() method when the button is clicked.


1 Answers

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> 

Also we can use "text" property of i to validate:

if(i.text == temp)

See it in action on codepen.

like image 144
Sébastien Avatar answered Sep 17 '22 21:09

Sébastien