c.k c.k - 7 months ago 22
jQuery Question

Set an option value as selected

I would like to load a select box where in the user's selected value will automatically appear.

I am receiving a Json data from the server with the user info.
sample of data is:


In my html code I have select option like this:

<select id="input_user" class="selectinput" disabled="true">
<option value="n/a"> n/a </option>
<option value="red"> red </option>
<option value="green"> green </option>
<option value="yellow"> yellow </option>
<option value="blue"> blue </option>
<option value="white"> white </option>
</select> //this will only show "n/a" as default

I tried this code to make the red value as default but not working.

var user_color= data[2].color; // this was from the json data
document.getElementById('input_user').selectedIndex = user_color;

Any help?


As you've tagged this question with jQuery you can just set the val() on the select directly:

var user_color = 'red'; //data[2].color;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="input_user" class="selectinput" disabled="true">
  <option value="n/a">n/a</option>
  <option value="red">red</option>
  <option value="green">green</option>
  <option value="yellow">yellow</option>
  <option value="blue">blue</option>
  <option value="white">white</option>