2
4

More than 3 years have passed since last update.

[Laravel] 入力フォームにJQuery-UIを使ってサジェスト機能を実装する

Posted at

概要

Laravelプロジェクトを作成後にマイグレーションすると生成されるusersテーブルのデータに対して、JQuery-UIを使ってサジェスト機能を実装するサンプルです。
こんな感じの、名前を途中まで打ち込むとDBから取得したデータを元にサジェストが出るフォームを作ります。
users_table.png

実装

コントローラー側は名前(nameカラム)のコレクションを取得してViewに渡します。

    public function showIndex()
    {
        $user = new User();
        $suggests = $user->select(['name'])->get();

        return view('index_view', compact('suggests'));
    }

View側はinputフォームの設置とautocompleteの設定を行います。
また、jQuery-UIを読み込むため<header>タグ内にGoogle Hosted Librariesからコピペしたリンクを貼ります。

<head>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
    <script>
        $(function() {
            $('#user_name').autocomplete({
                source: @JSON($suggests).map(item => ({
                    label: item.name,
                    value: item.name,
                })),
                autoFocus: true,
                delay: 300,
                minLength: 2
            });
        });
    </script>

    <input id="user_name" type="text" />
</body>

以上です、ありがとうございました。

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