Value Based Option Selection

I am trying to figure out a way to automatically select an option based on the passed variable that matches only the value of this option.

JS Fiddle Link Demo

<label>
    <span>Font Type</span>
    <select id="options>
        <option value="one">One</option>
        <option value="two" selected>Two</option>
        <option value="three">Three</option>
    </select>
</label>

function loadSelect(userFont){
    $('#options').find('option[value='+userFont+']').attr('selected', 'selected');
}

loadSelect(three);
+4
source share
1 answer

Just set the value in the tag <select>:

$('#options').val(userFont);

$(function() {
  $("#options").val("three");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="options">
  <option value="one">One</option>
  <option value="two" selected>Two</option>
  <option value="three">Three</option>
</select>
Run code
+1
source

All Articles