选择2版本4.0允许用户输入自由文本

时间:2015-05-03 21:22:06

标签: jquery jquery-select2 jquery-select2-4

我使用的是最新版本的Select2:Select2 4.0

我想允许用户输入自由文本。换句话说,如果用户在下拉列表中找不到选项(ajax返回的数据),我希望他们能够“选择”他们输入的任何文本。

这是我的标记:

<select class="required form-control" id="businessName" data-placeholder="Choose An Name" > </select> 

这是我用来初始化Select2的JavaScript:

$("#businessName").select2({
    ajax: {
      url: "/register/namelookup",
      dataType: 'json',
      delay: 250,
      type: 'post',
      data: function (params) {
        return {
          businessName: params.term, // search term
          page: params.page
        };
      },
      processResults: function (data, page) {
        return {
          results: data.items
        };
      },
      cache: false
    },
    escapeMarkup: function (markup) { return markup; },
    minimumInputLength: 4,
    createSearchChoice:function(term, data) {
        if ( $(data).filter( function() {
          return this.text.localeCompare(term)===0;
        }).length===0) {
          return {id:term, text:term};
        }
    },
});

我添加了createSearchChoice,但它不起作用。我也看了this answer,但到目前为止还没有运气。

1 个答案:

答案 0 :(得分:29)

这是4.0.0中由于3.x中无证件行为导致的更改。在3.x中,如果您使用的是createSearchChoice,那么使用tags(将其设置为true或空数组)。这是因为createSearchChoicetags捆绑在一起。

在4.x中,createSearchChoice已重命名为createTag,因为它确实正在创建标记。这在4.0.0-beta.2 release notes中有记录。此外,createSearchChoice的第二个(也是未记录的)参数从未实现过 - 但在这种情况下您实际上并不需要它。

因此,注意到这两个更改,允许用户添加新选项的工作代码是

$("#businessName").select2({
    ajax: {
      url: "/register/namelookup",
      dataType: 'json',
      delay: 250,
      type: 'post',
      data: function (params) {
        return {
          businessName: params.term, // search term
          page: params.page
        };
      },
      processResults: function (data, page) {
        return {
          results: data.items
        };
      },
      cache: false
    },
    escapeMarkup: function (markup) { return markup; },
    minimumInputLength: 4,
    tags: true
});

请注意,我没有实现createTag,这是因为the default implementation与您原来createSearchChoice尝试的内容相匹配。我确实添加了tags: true,因为仍然需要它才能使它工作。

最重要的是,由于您已更改为<select>,因此确实存在一些无效标记。

<select class="required form-control" id="businessName" data-placeholder="Choose An Name" ></select>

type属性(以前设置为hidden)仅在您使用<input /><select>无效时才需要。这不应该对你做出任何明显的改变。