Bootstrapを使っている環境にて、select要素の見栄えを良くしたい場合、 bootstrap-select
を使うことがあります。
snapappointments/bootstrap-select: The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more.
bootstrap-selectにはいくつかイベントがあり、例えば changed.bs.select
を使うと選択した値が変更された時にイベントが発火します。
https://developer.snapappointments.com/bootstrap-select/options/#events
ドキュメントにもある通り previousValue
には変更前の値が入ってきます。
ただ、1.13.8以前の古いバージョンを使っている場合、previousValueが取得できなかったため、メモを残します。
目次
環境
- Bootstrap 4.3.1
- bootstrap-select 1.13.8/1.13.9
- jQuery 3.5.1
- popper 1.14.7
原因
以下にある通り、バグがあったようです。
- javascript - Bootstrap select doesn't return clickedIndex on changed.bs.select - Stack Overflow
- val() method doesn't fire changed.bs.select · Issue #1303 · snapappointments/bootstrap-select
- val() method fires changed.bs.select, but the select's previousValue is not passed through · Issue #2244 · snapappointments/bootstrap-select
対応
bootstrap-selectを1.13.9以降にアップデートします。
再現
以下のようなHTMLがあるとします。
<div style="padding: 10px"> <div> <h1>1.13.8</h1> <select id="ringo" class="selectpicker"> <option value="1">フジ</option> <option value="2">紅玉</option> <option value="3">シナノゴールド</option> </select> </div> <div style="padding-top: 10px"> <button id="auto" class="btn btn-primary">自動選択</button> </div> </div>
表示はこんな感じ。
ここで、
$(document).ready(function() { $('#ringo').on('changed.bs.select', (event, clickedIndex, isSelected, previousValue) => { console.log(previousValue); }); $('#auto').on('click', () => { $('#ringo').selectpicker('val', 3); }) });
と、自動選択ボタンを押すと、 シナノゴールド
が表示されるようにします。
また、 changed.bs.select
の発火を確認するため、イベントが発生したら previousValue
の値をコンソールに出力します。
bootstrap-selectのバージョンが1.13.8の場合
undefined
になります。
bootstrap-selectのバージョンが1.13.9の場合
正しい値 1
(フジ) が取得できます。
ソースコード
Githubにあげました。
https://github.com/thinkAmi-sandbox/bootstrap_select-sample