Cuộc sống Nhật Bản
Yuto Blog

Ruby on Rails 7でselect2を導入方法

HSBC - Mở thẻ tín dụng
Nội dung chính

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

select2とjQueryインストール

Copy
1
yarn add select2 jquery
select2 コントローラー作成
Copy app/frontend/controllers/select2_controller.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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();
    });
  }
}

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

viewsで適用

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

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

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

Copy app/assets/stylesheets/select2.scss
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$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;
  }
}
Updated at 2023-05-09
Nếu bài viết có ích thì các bạn hãy chia sẻ nhé
Rate this article: 5/5 (14 ratings)
You didn't rate yet
Le Minh Thien Toan

Tác giả:Yuto Yasunaga

Xin chào các bạn. Mình là kỹ sư IT đang làm việc ở Nhật Bản. Mình tạo blog này để chia sẻ về cuộc sống và những kinh nghiệm trong quá trình học tập và làm việc.
Hy vọng bài viết này sẽ có ích cho bạn.