一連の値を含むドロップダウンが必要ですが、ユーザーがそこにリストされていない新しい値を「選択」できるようにします。
モードで使用している場合、select2tags
はこれをサポートしているようですが、タグを使用せずにそれを行う方法はありますか?
一連の値を含むドロップダウンが必要ですが、ユーザーがそこにリストされていない新しい値を「選択」できるようにします。
モードで使用している場合、select2tags
はこれをサポートしているようですが、タグを使用せずにそれを行う方法はありますか?
@fmpwizardによって提供された優れた回答は Select2 3.5.2 以下で機能しますが、 4.0.0 では機能しません。
非常に早い段階から (ただし、おそらくこの質問ほど早くはありません)、Select2 は「タグ付け」をサポートしてきました。つまり、ユーザーが許可すれば、ユーザーが独自の値を追加できる場所です。tags
これはオプションで有効にすることができ、ドキュメントの例で遊ぶことができます。
$("select").select2({
tags: true
});
デフォルトでは、これにより、入力した検索用語と同じテキストを持つオプションが作成されます。特別な方法でマークしたい場合に使用するオブジェクトを変更したり、選択したオブジェクトをリモートで作成したりできます。
$("select").select2({
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
}
});
イベントを介して渡されたオブジェクトで簡単に見つけられるフラグとして機能することに加えてselect2:select
、追加のプロパティを使用すると、結果でオプションをわずかに異なる方法でレンダリングすることもできます。そのため、" (new) " を隣に置くことで、それが新しいオプションであるという事実を視覚的に知らせたい場合は、次のようにすることができます。
$("select").select2({
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
$result.append(" <em>(new)</em>");
}
return $result;
}
});
バージョン4以降については、KevinBrownによる以下の回答を確認してください。
Select2 3.5.2以下では、次のようなものを使用できます。
$(selector).select2({
minimumInputLength:1,
"ajax": {
data:function (term, page) {
return { term:term, page:page };
},
dataType:"json",
quietMillis:100,
results: function (data, page) {
return {results: data.results};
},
"url": url
},
id: function(object) {
return object.text;
},
//Allow manually entered text in drop down.
createSearchChoice:function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
});
(select2メーリングリストの回答から取得しましたが、現在リンクが見つかりません)
@fmpwizard の回答の改善:
//Allow manually entered text in drop down.
createSearchChoice:function(term, data) {
if ( $(data).filter( function() {
return term.localeCompare(this.text)===0; //even if the this.text is undefined it works
}).length===0) {
return {id:term, text:term};
}
},
//solution to this error: Uncaught TypeError: Cannot read property 'localeCompare' of undefined
助けてくれてありがとう、私はCodeigniter II内で以下のコードを使用し、バージョンを使用しています:select2の3.5.2。
var results = [];
var location_url = <?php echo json_encode(site_url('job/location')); ?>;
$('.location_select').select2({
ajax: {
url: location_url,
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
results = [];
$.each(data, function(index, item){
results.push({
id: item.location_id,
text: item.location_name
});
});
return {
results: results
};
}
},
//Allow manually entered text in drop down.
createSearchChoice:function(term, results) {
if ($(results).filter( function() {
return term.localeCompare(this.text)===0;
}).length===0) {
return {id:term, text:term + ' [New]'};
}
},
});