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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22410180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:56:11  来源:igfitidea点击:

How to allow user to select empty string on Select2

jqueryjquery-select2

提问by Smith

The texbox is dynamically filled with a remote call using Select2 and I want to allow users to leave the field blank.

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

$("#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};
        }
    },
 });

Here is working example http://ivaynberg.github.io/select2/index.html#ajax

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

回答by John S

You can set the allowClearoption to true.

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

$("#e6").select2({
    allowClear: true,
    placeholder: "Search for a movie",
    ...

When set to true, the allowClearoption causes the Select2 control to display a clear button, but you must also specify the placeholderoption for it to work.

当设置为 时true,该allowClear选项会导致 Select2 控件显示一个清除按钮,但您还必须指定该placeholder选项才能使其工作。

Here's a jsfiddleshowing it work for a Select2 that uses ajax.

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

回答by user2306059

This worked for me,

这对我有用,

$('#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}
        ]
      }
    ]
  }
);

回答by imsinu9

Suppose You are using FormtasticNormally with Active Admin You can pass during declaration

假设您通常在 Active Admin中使用Formtastic您可以在声明期间通过

f.input :your_select_2_field, { as: :select2, collection: ['a', 'b'], include_blank: 'Select Nothing'}

Concentrate On Curly Braces {}

专注于花括号 {}