A slight variation of blushrt's answer for when you do not have "hard coded" values for options (i.e. 1, 2, 3, 4 etc.)
Let's say you render a <select>
with options values being GUIDs of some users. Then you will need to somehow extract the value of the option in order to set it on the <select>
.
In the following we select the first option of the select.
HTML:
<select name="selValue" class="selectpicker">
<option value="CD23E546-9BD8-40FD-BD9A-3E2CBAD81A39">Dennis</option>
<option value="4DDCC643-0DE2-4B78-8393-33A716E3AFF4">Robert</option>
<option value="D3017807-86E2-4E56-9F28-961202FFF095">George</option>
<option value="991C2782-971E-41F8-B532-32E005F6A349">Ivanhoe</option>
</select>
Javascript:
// Initialize the select picker.
$('select[name=selValue]').selectpicker();
// Extract the value of the first option.
var sVal = $('select[name=selValue] option:first').val();
// Set the "selected" value of the <select>.
$('select[name=selValue]').val(sVal);
// Force a refresh.
$('select[name=selValue]').selectpicker('refresh');
We used this in a select with the multiple keyword <select multiple>
. In this case nothing is selected per default, but we wanted the first item to always be selected.