5
6

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でマルチ選択できるセレクトボックスを作ってみる

Posted at

完成図

manage.gif

Slect2はjQueryのセレクトボックスを作ってくれるプラグインです

バッサリした訳:いろいろオプションがあってカスタマイズできるセレクトボックスが作れるよ

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.
Getting Started | Select2 - The jQuery replacement for select boxes

CDNを使えば速攻で使えるようになります

マルチ選択できるセレクトボックスを作ります

mySelect2.html
<!DOCTYPE html>
<html>
<head>
    <!-- jQueryの読み込み -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!-- Select2の読み込み -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    <script type="text/javascript" src="js/mySelect2.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
    <title>はじめてのSelect2でマルチ選択できるセレクトボックスを作ってみる</title>
</head>
<body>
    <!-- Select2で作るセレクトボックス -->
    <select class="pillbox" multiple="multiple"></select>
</body>
</html>
mySelect2.js
/**
 * セレクトボックスの中身.
 * @type {Object}
 */
var sentakushi = {
    monkey : 'さる',
    rabbit : 'うさぎ',
    possum : 'ふくろねずみ',
    ponsuke : 'ぽんすけ'
};

/**
 * DOM要素が読み込まれてからSelect2でセレクトボックスを作るため$(document).ready()で実行する.
 */
$(document).ready(function() {
    // セレクトボックスの中身を設定する.
    let options = $.map(sentakushi, function(text, value) {
        let option = $('<option>', {value: value, text: text});
        return option;
    });
    $('.pillbox').append(options);
    // Select2でセレクトボックスをつくる.
    $('.pillbox').select2();
});
5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?