如何允许用户在Select2上选择空字符串

Smi*_*ith 20 jquery jquery-select2

使用Select2通过远程调用动态填充texbox,我希望允许用户将该字段留空.

$("#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};
        }
    },
 });
Run Code Online (Sandbox Code Playgroud)

这是一个工作示例http://ivaynberg.github.io/select2/index.html#ajax

Joh*_*n S 62

您可以将allowClear选项设置为true.

$("#e6").select2({
    allowClear: true,
    placeholder: "Search for a movie",
    ...
Run Code Online (Sandbox Code Playgroud)

设置为时true,该allowClear选项会使Select2控件显示清除按钮,但您还必须指定placeholder其工作选项.

这是一个jsfiddle,显示它适用于使用ajax的Select2.


小智 6

这对我有用,

$('#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}
        ]
      }
    ]
  }
);
Run Code Online (Sandbox Code Playgroud)