やりたいこと
Select2というライブラリを用いて、
テキストボックスにテキストを入力したら、
ajaxを使って非同期で検索を行い、
検索結果をSelectBoxで一覧表示。
その後、選択をしたいです。
イメージとしては
https://select2.github.io/examples.html#tagsのLoading Remote Dataの処理をさせたいです。
現状
ajaxを用いて、リクエストを送り、それに対してのレスポンスは返ってきており、
それを一覧で表示させるところまではできております。
問題はその一覧を選択できずフォーカスも当たりません。

オプションに問題があるとは思うのですが、
ドキュメントや他の人の実装を見てもわからなかったので、どこがおかしいのかご教授お願い致します。
下記のコードはサンプルを参考にしています。
こちらでは問題なく動作が行われます。
$(".s-select").select2({ ajax: { url: "https://api.github.com/search/repositories", dataType: 'json', delay: 250, data: function (params) { return { q: params.term, // search term page: params.page }; }, processResults: function (data, params) { console.log(data.items); return { results: data.items, }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 1, templateResult: formatRepo, // omitted for brevity, see the source of this page }); function formatRepo(repo){ var markup = "<div class='select2-result-repository clearfix'>" + repo + "</div>"; return markup; } });
一方こちらのコードが表示結果が選択できず、フォーカスも当たりません。
ajax: { method:"POST", url: "/company/select", dataType: 'json', data: function (params) { return { companyName: params.term, // search term }; }, processResults: function (data, params) { console.log(data) return { results: data, }; }, cache: true }, escapeMarkup: function (markup) { console.log(markup); return markup; }, // let our custom formatter work minimumInputLength: 1, templateResult: formatRepo, // omitted for brevity, see the source of this page templateSelection:formatRepoSelection, }); function formatRepo (repo) { var markup = "<div class='select2-result-repository clearfix'>" + repo.companyName + "</div>"; return markup; } function formatRepoSelection(repo){ return repo; }
違いは、GETかPOSTかの違いだけかと思っております。
お力添えの程、宜しく御願い致します。
formatRepo の定義をご提示ください。
大変失礼致しました。formatRepoの定義を追加致しました。現状は"https://select2.github.io/examples.html#tags"のものをほぼそのまま利用しております。
不具合を回答者が手元で再現できるようなミニマムコードを提示してください。
一覧で選択した値がセットされず空白のまま…ということで宜しいですかね?そもそもフォーカスすら当たらない?とりあえずtemplateSelectionの実装を追記お願い致します。
yagさん> そもそもフォーカスが当たりません。サンプルの方もtemplateSelectionの実装をせずともフォーカスが当たっておりましたので、実装をしておりませんでした。templateSelectionは必須なのでしょうか?
こちらでサンプル作ってみましたところ、値をセレクトボックスにセットする為にはformatRepoSelectionが必要なようです。恐らくですがそれで解決する気もしますので試してみてください。
yagさん>追加してみましたが、何も変わりなかったです。GitHubに載っているコード(https://github.com/select2/select2/blob/master/dist/js/select2.js)の4879行目にあるのがデフォルトで設定されるものかなと思ったので、設定しなくてもいいのかなと思ってました。
あなたの回答
tips
プレビュー