0

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.

Community
  • 1
  • 1
tomorin
  • 157
  • 1
  • 6
  • is the test click even called? otherwise code seems correct – Mike B Sep 07 '16 at 18:08
  • Try `document.getElementById('preffrom').value='p03';` – Vijai Sep 07 '16 at 18:09
  • @Mikelis Baltruks Yes. And I also tested it using by DevTool's console. But it seems to be removed a `selectpicker`'s id when `$('#preffrom').val('p03')` executed. Besides this, I modified it like this: $('.selectpicker').val('p03'); But it didn't work. Btw, this code works correctly: $(".selectpicker").val("宮城県"); But I want to do it by id value. – tomorin Sep 07 '16 at 18:36
  • @Vijai Thanks, but It seems to have changed the selectpicker's id value. – tomorin Sep 07 '16 at 18:42

1 Answers1

1

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/

Pat
  • 2,540
  • 1
  • 21
  • 28