tomorin tomorin - 2 months ago 21
Javascript Question

How to set a selected value by using id on selectpicker plugin from bootstrap

I'm testing the selectpicker plugin of bootstrap like this:

HTML

<select class="selectpicker form-control" id="preffrom">
<optgroup label="北海道" class="area-hokkaido">
<option id="p01">北海道</option>
</optgroup>
<optgroup label="東北" class="area-tohoku">
<option id="p02">青森県</option>
<option id="p03">岩手県</option>
...
<option id="p07">福島県</option>
</optgroup>
...
<optgroup label="沖縄" class="area-okinawa">
<option id="p47">沖縄県</option>
</optgroup>
</select>


JavaScript

$(function(){
$('.selectpicker').selectpicker();
// this event is for test but it does not work...
$('#test').bind('click', function(e){
$('#preffrom').val('p03');
$('#preffrom').selectpicker('refresh');
});
});


I referenced this:
How to set selected value on select using selectpicker plugin from bootstrap

But nothing happens.
Please tell me correct way to select an
option
using id value.

Pat Pat
Answer

If all you are trying to do is selected the #p03 option then $('#p03').prop('selected', true); should work (instead of $('#preffrom').val('p03');). Here is a working example: https://jsfiddle.net/kwm9rsee/

Comments