select2 下拉列表是否支持使用 ajax 并允许用户输入新值?

Does select2 dropdown support using ajax and allowing users to enter in new values?

am using select 2 效果很好。我有一个示例,其中用户通过 ajax 从下拉列表中进行选择(与 link 中列出的远程数据示例完全一样),但我希望用户能够搜索以及能够输入后端不存在的新值。

我在多选上工作,但想看看在使用单个下拉选项时是否有相同的支持?

这是代码:

$(".js-example-tags").select2({
  tags: true,
});

并从 select2 中删除多个属性。

我希望这会奏效

据我了解,您想要的是使用 single select 框,让用户能够从 ajax 来源 select 并且能够自由输入文本.

此外,您已经让 ajax 部分正常工作,您唯一想知道的是添加用户输入的 free text

这里有一个Working Fiddle Select2使用的插件版本是4.0.3

如此有效的片段

$(".js-data-example-ajax").select2({
  language: {
    noResults: function() {
      return "No results found, <a id='newData' href='#' class='btn btn-xs btn-success'>Use the above text anyways</a>";
    }
  },
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function(params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function(data, params) {
      params.page = params.page || 1;

      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  escapeMarkup: function(markup) {
    return markup;
  },
  minimumInputLength: 1,
  templateResult: formatRepo,
  templateSelection: formatRepoSelection,
  createTag: function(params) {
    alert('create tag');
    return {
      id: params.term,
      text: params.term,
      newOption: true
    }
  }
});

$(document).on('click', '#newData', function() {
  var $select2 = $(".js-data-example-ajax");
  debugger;
  var newStateVal = $select2.siblings("span.select2-container").find("input.select2-search__field").val();
  if ($select2.find("option[value=" + newStateVal + "]").length) {
    $select2.val(newStateVal).trigger("change");
    $select2.select2('close');
  } else {
    // Create the DOM option that is pre-selected by default
    var newState = new Option(newStateVal, newStateVal, true, true);
    // Append it to the select
    $select2.append(newState).trigger('change');
    $select2.select2('close');
  }
});


function formatRepo(repo) {
  if (repo.loading) return repo.text;

  var markup = "<div class='select2-result-repository clearfix'>" +
    "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
    "<div class='select2-result-repository__meta'>" +
    "<div class='select2-result-repository__title'>" + repo.full_name + "</div>";

  if (repo.description) {
    markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
  }

  markup += "<div class='select2-result-repository__statistics'>" +
    "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +
    "<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
    "<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
    "</div>" +
    "</div></div>";

  if (repo.newOption) {
    alert('adasdasddads');
  }

  return markup;
}

function formatRepoSelection(repo) {
  return repo.full_name || repo.text;
}
.select2-container {
  width: 100% !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://select2.github.io/css/s2-docs.css" rel="stylesheet" />
<script src="https://select2.github.io/vendor/js/bootstrap.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://select2.github.io/css/bootstrap.css" rel="stylesheet" />

<select class="js-data-example-ajax">
  <option value="3620194" selected="selected">select2/select2</option>
</select>

所需的更改是。

1) 我们需要更改自定义消息 No results found 的显示方式。我们需要在这里有一个选项,说明无论如何都要添加键入的文本。因此,添加 language 选项并在此添加 noResults 选项,并在未找到结果时提供自定义消息。在此自定义消息中,我们添加了一个 button,为此我们编写了进一步的逻辑,以将此自由键入的文本添加到我们的下拉列表中。

代码如下

$(".js-data-example-ajax").select2({
  language: {
    noResults: function() {
      return "No results found, <a id='newData' href='#' class='btn btn-xs btn-success'>Use the above text anyways</a>";
    }
  },
  //... your other setting
};

在找不到匹配项时添加此设置,插件的结果为

2) 现在有了上面的更改,我们需要添加额外的代码来处理按钮的点击事件,以将这个新选项添加​​到我们的插件中。代码如下

$(document).on('click', '#newData', function() {
  var $select2 = $(".js-data-example-ajax");      
  var newStateVal = $select2.siblings("span.select2-container").find("input.select2-search__field").val();
  //Get the new value.
  if ($select2.find("option[value=" + newStateVal + "]").length) { //if already present just select it
    $select2.val(newStateVal).trigger("change");
  } else {
    // Create the DOM option that is pre-selected by default
    var newState = new Option(newStateVal, newStateVal, true, true);
    // Append it to the select
    $select2.append(newState).trigger('change');
    $select2.select2('close');
  }
});

有了这个,插件能够 selecting 来自 ajax 的值以及自由类型形式。这是一个 select 示例,因为这就是您想要的。

希望对您有所帮助!!

Here is example from select2 documentation

$(".js-data-example-ajax").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, params) {
      // parse the results into the format expected by Select2
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data, except to indicate that infinite
      // scrolling can be used
      params.page = params.page || 1;

      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  minimumInputLength: 1,
  templateResult: formatRepo, // omitted for brevity, see the source of this page
  templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});