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

【Laravel + Blade】select2 を使うときはwindow.jQueryとかjQuery.fn.select2の確認

Last updated at Posted at 2025-11-10

フォームの を検索可能なプルダウンにするためにselect2を利用する。
下記が参考コード。
下記のコードを整理しておく。

@push('js')
<script>
document.addEventListener('DOMContentLoaded', function() {
    if (!window.jQuery || !jQuery.fn.select2) {
        return;
    }
    var $company = jQuery('#company_id');
    if (!$company.length || $company.data('select2')) {
        return;
    }
    $company.select2({
        placeholder: '会社を選択',
        allowClear: true,
        width: '100%',
        language: {
            noResults: function() {
                return '該当する会社が見つかりません';
            },
            searching: function() {
                return '検索中...';
            }
        }
    });
});
</script>
@endpush
コード 意味 必要な理由
!window.jQuery jQuery が読み込まれていない jQuery が無い状態で .select2() を呼ぶとエラーになるため
!jQuery.fn.select2 select2 が読み込まれていない select2 の機能が存在しないとプラグインを使えないため
jQuery('#branch_id') select2 を適用したい <select> を取得 DOM 要素を操作するため
$branch.data('select2') select2 がすでに適用済みか確認 二重初期化(重複適用)を防ぐため

1. jQuery / select2 があるか確認する

if (!window.jQuery || !jQuery.fn.select2) {
    return;
}
  • window.jQuery → jQuery本体があるかを確認
  • jQuery.fn.select2 → select2 プラグインが使えるかを確認

どちらか無ければ 安全に終了 します。

2. 対象となる を取得する

var $branch = jQuery('#branch_id');

これはただのDOM取得。

...

↑ このタグを $branch という変数として扱えるようにしています。

3. 要素があるかと、select2 がすでに適用されていないか確認

if (!$branch.length || $branch.data('select2')) {
    return;
}
条件 意味
!$branch.length branch_id の要素が存在しない(ビューに <select id="branch_id"> が無い場合)
$branch.data('select2') すでに select2 が適用済み

例えば同じ画面に複数回 JS が読み込まれたときでも、二重で select2 を適用しないようにしている。

4. select2 を適用する

$branch.select2({
    placeholder: '支店を選択',
    allowClear: true,
    width: '100%',
    language: { ... }
});

→ これで 検索可能ドロップダウンに変更できる

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