LoginSignup
1
1

More than 1 year has passed since last update.

Ruby on Rails 7でselect2を導入方法

Last updated at Posted at 2022-01-26

Webpackerの場合はこちらの記事です

select2とjQueryインストール

yarn add select2 jquery

select2 コントローラー作成

app/frontend/controllers/select2_controller.js
import { Controller } from "@hotwired/stimulus"
import $ from 'jquery';
import 'select2/dist/css/select2.min.css'
import Select2 from "select2"

export default class extends Controller {
  connect() {
    Select2()
    $('.js-select2').select2()
    // select2ドロップダウンをクリックすると入力フィールドにフォーカスする
    $(document).on('select2:open', () => {
      document.querySelector('.select2-search__field').focus();
    });
  }
}

app/frontend/controllers/index.js
import Select2Controller from "./select2_controller"
application.register("select2", Select2Controller)
app/frontend/entrypoints/application.js
import '../controllers'

viewsで適用

select2を使いたいセレクトボックスに data-controller="select2"とCSSクラスjs-select2を適用

*.html.slim
      div data-controller="select2"
        = f.input :product_id,
          collection: Product.all,
          include_blank: false,
          input_html: { class: 'js-select2' }

任意:スタイルを改善する

app/assets/stylesheets/select2.scss
$select2-height: 38px;

.select2-container {
  .select2-selection--single {
    height: $select2-height;
    line-height: $select2-height;
    .select2-selection__arrow, .select2-selection__rendered {
      height: $select2-height;
      line-height: $select2-height;
    }
  }
  .select2-search--dropdown .select2-search__field {
    font-size: 16px;
    padding: 4px;
  }
}
1
1
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
1
1