Select2 3.5.2 から Select2 4.0.0 に移行する際は、リリース ノートと4.0 のリリース通知を読むことを強くお勧めします。
バージョン 3.5.2 では、データを検索するときに下線の一致を再現できます (formatSelection と query.term を使用)。v4.0.0 でそれを作成する方法 (関数 templateResult は「結果」のみを渡し、「クエリ」は渡さない) ?
結果がクエリから分離されたため、これは 4.0 で削除されたため、情報を渡し続ける意味がありませんでした。もちろん、これはクエリを取得して保存できないという意味ではありません。あなたがする必要があるのは、クエリを保存することだけです。次のようなものがうまくいくかもしれません
var query = {};
var $element = $('#my-happy-select');
function markMatch (text, term) {
// Find where the match is
var match = text.toUpperCase().indexOf(term.toUpperCase());
var $result = $('<span></span>');
// If there is no match, move on
if (match < 0) {
return $result.text(text);
}
// Put in whatever text is before the match
$result.text(text.substring(0, match));
// Mark the match
var $match = $('<span class="select2-rendered__match"></span>');
$match.text(text.substring(match, match + term.length));
// Append the matching text
$result.append($match);
// Put in whatever is after the match
$result.append(text.substring(match + term.length));
return $result;
}
$element.select2({
templateResult: function (item) {
// No need to template the searching text
if (item.loading) {
return item.text;
}
var term = query.term || '';
var $result = markMatch(item.text, term);
return $result;
},
language: {
searching: function (params) {
// Intercept the query as it is happening
query = params;
// Change this to be appropriate for your application
return 'Searching…';
}
}
});
バージョン 3.x では、(createSearchChoice を使用して) リストにない検索値を使用して、無料のエントリを追加できます。V4.0 にはこのオプションがありません。再度作成する方法はありますか?
これは、4.0 でもtags
オプション ( に設定true
) を使用して行うことができます。タグをカスタマイズしたい場合は、createTag
( と同様createSearchChoice
) を使用できます。
var $element = $('#my-happy-select');
$element.select2({
createTag: function (query) {
return {
id: query.term,
text: query.term,
tag: true
}
},
tags: true
});