2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】Tom Selectでテキストボックスに複数のテキストを入力させる

Last updated at Posted at 2025-02-05

どうもこんにちは。

今回はTom Selectというライブラリを使用して、テキストボックスに複数のテキストを入力できるように実装したので、その備忘録として残しておきます。

経緯

元々、Select2というライブラリを使用して、テキストボックスに複数のテキストを入力できるように実装していましたが、IMEがONになっている状態で入力すると、以下のように正常に入力できない現象が発生していました。

image.png

一見テキストボックスに見えますが、コード上ではセレクトボックスとして実装しています。これが気に食わなかった...

Tom Select

Tom Selectの場合は、テキストボックスはテキストボックスとしてコーディングすることができるので楽でした。

導入方法は以下です。

1. importmap.rb

CDN経由でライブラリをインストールするようにしました。

config/importmap.rb
pin "tom-select", to: "https://cdn.jsdelivr.net/npm/tom-select@2.4.2/dist/js/tom-select.complete.min.js"

2. application.js

app/javascript/application.js
import "tom-select";

3. tom-select.css

以下のURLから、CSSのスタイル定義をコピーして、app/assets/stylesheetsディレクトリ配下におきます。(ファイル名はtom-select.cssとします。)

4. application.css.scss

app/assets/stylesheets/application.css.scss
*= require tom-select

5. (必要があれば)rails assets:precompile

$ rails assets:precompile

プリコンパイルしたらrailsサーバを再起動

6. 要素を指定してtom-selectを適用

function initializeTomSelect(selector) {
    const el = document.querySelectorAll(selector);
    el.forEach(function(e) {
        new window.TomSelect(e, {
            persist: false,
            createOnBlur: true,
            create: true,
            maxItems: null,
            placeholder: '選択肢を入力',
            delimiter: ','
        });
    });
}

このままだとイメージ通りの動作をしなかったので、CSSスタイルを上書きしました。

#field_options_text.field-options .field-options-text {
  width: 100%;
  flex: 1;
  min-width: 500px;
}

.ts-control input {
  width: 100%;
}

.ts-hidden-accessible {
  display: none !important;
}

これで以下のように動作しました。

スクリーンショット 2025-02-01 19.19.23.png

以上

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?