【问题标题】:How to allow user to select empty string on Select2如何允许用户在 Select2 上选择空字符串
【发布时间】:2014-04-20 01:12:06
【问题描述】:

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};
        }
    },
 });

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

【问题讨论】:

  • 请不要链接到代码——把你的代码放在这里,尽量减少重现问题
  • @RUJordan 感谢提醒,已包含代码

标签: jquery jquery-select2


【解决方案1】:

您可以将allowClear 选项设置为true

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

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

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

【讨论】:

  • 谢谢,这正是我想要的。
  • “占位符”没问题,我将其分配为空字符串。
  • @sc89 - 它适用于 ajax。看到这个jsfiddle
  • @sc89 - 我看到了你的代码,但没有发现任何明显的不同。这是一个尽可能接近您的代码的jsfiddle
  • 哦,我的约翰,你是对的,我很愚蠢,我犯了将选项放入 ajax 选项本身的错误......我很抱歉。删除了我的 cmets 以避免任何未来的混乱。
【解决方案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}
        ]
      }
    ]
  }
);

【讨论】:

  • 此代码更好,因为在未选择任何内容时将 id 发送到后端。
【解决方案3】:

假设您正在使用Formtastic 通常与 Active Admin 一起您可以在声明期间通过

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

专注于花括号{}

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 2017-12-06
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 2014-06-21
    • 1970-01-01
    相关资源
    最近更新 更多