17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

select2 Tips メモ

Last updated at Posted at 2016-02-19

jQueryライブラリのselect2 https://select2.github.io/ は便利ですが、
ググっても古い情報か英語だったりするのでメモ。

値を設定する

普通に設定してもプルダウンが連動しないので、change を呼び出す。

var $select = $('.hoge').select2({});
// 値を設定する
$select.val("1").trigger('change');

フォーカス時にプルダウンを開く

var $select = $('.hoge').select2({});
// フォーカス時にプルダウンを開く
var select2Focus = function(){
  $(this).closest('.select2').prev('select').select2('open');
};   
$select.next('.select2').find('.select2-selection')
.one('focus', select2Focus).on("blur", function () {
  $(this).one('focus', select2Focus)
});

keypressイベントを付け替える(追記 20170826)

ver4.0.0で確認

var $select = $('.hoge').select2({});
// Select2のデータオブジェクトは 以下のように取得する
var select2 = $select.data('select2');
// 元々のkeypressイベント
var keypress = select2.listeners.keypress[0];
							
// 現在のイベントを消す
select2.listeners.keypress=[];
// select2イベント登録。jQueryのものとは若干動作が異なるので注意
select2
.on('keypress', function(evt) {
  // 例えば Enterキーで開くを無効にする
  if (evt.which==13) {
    if (!select2.isOpen()){ 
      return;
    }									
  }
  // それ以外なら元々のイベントを呼び出してみる
 keypress.apply(this, [evt]);
});

keyupイベントを追加してみる(追記 20170826)

ver4.0.0で確認。
定義されているイベント(keypress)とそうでないもの(keyup)がある。

var $select = $('.hoge').select2({});
// Select2のデータオブジェクトは 以下のように取得する
var select2 = $select.data('select2');
// select2には幾つかjQueryオブジェクトがある。$selectionはそれの一つ。
select2.$selection.on('keyup',function(evt){
  if (evt.which==13) {
    if (!select2.isOpen()){
      // 例えば、開いていないとき、Enterキーで何かする
      return;
    }
  }
});						
17
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?