Set the parameter value

I would like to load a selection window in which the value selected by the user will be automatically displayed.

I get Json data from a server with user information. sample data:{"color":"red"}

In my html code, I have a selection option:

<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 default, but it doesn’t work.

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

Any help?

+4
source share
2 answers

As you noted this question with jQuery, you can simply install val()in selectdirectly:

var user_color = 'red'; //data[2].color;
$('#input_user').val(user_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>
</select>
Run codeHide result
+7
source

after much research, I finally returned to the jQuery documentation, which gave me the correct answer:

1/ , 'selected'

function remove_selected(){
  $("select option").removeAttr('selected');
}

2/ prop() jQuery, 'selected'

// USE THE FUNCTION TO REMOVE ALL ATTRIBUTES ALREADY SELECTED  
remove_selected();

// Set the tag <option> attribute to 'selected'
$('select option[value="ThatYouWant"]').prop({defaultSelected: true});

HTML :

<select>
  <option value="something">Something</option>
  <option value="ThatYouWant" selected>That you want</option>
  <option value="OtherValue">Other value</option>
</select>

, , , . , .

: https://api.jquery.com/prop/

+1

Source: https://habr.com/ru/post/1648619/


All Articles