使用Select2动态填充远程调用的文本框ID,我希望允许用户将该字段留空。
$("#e6").select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
ajax: {
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
};
},
results: function (data, page) {
return {results: data.movies};
}
},
});
答案 0 :(得分:57)
您可以将allowClear
选项设置为true
。
$("#e6").select2({
allowClear: true,
placeholder: "Search for a movie",
...
设置为true
时,allowClear
选项会使Select2控件显示清除按钮,但您还必须指定placeholder
选项才能生效。
这里有一个jsfiddle,显示它适用于使用ajax的Select2。
答案 1 :(得分:2)
这对我有用,
$('#f').select2(
{
allowClear: true,
placeholder: {
id: "-1",
text:"City",
selected:'selected'
},
data:[
{id: -1,text: '',selected: 'selected',search:'',hidden:true},
{ id: 1,
text: 'Italy',
search: "Italy",
children: [
{id: 2, text: 'Sardinia', search: "Italy Sardinia", selected: false},
{id: 3, text: 'Sicily', search: "Italy Sicily", selected: false}
]
},
{
id: 4,
text: 'United Kingdom',
search: "United Kingdom",
children:[
{id: 5, text: 'Guernsey', search: "United Kingdom - Guernsey", selected: false},
{id: 6, text: 'Jersey', search: "United Kingdom - Jersey", selected: false}
]
}
]
}
);
答案 2 :(得分:0)
假设您正在使用Formtastic通常使用Active Admin您可以在声明期间传递
f.input :your_select_2_field, { as: :select2, collection: ['a', 'b'], include_blank: 'Select Nothing'}
专注于卷曲大括号{}