select2下拉支持使用ajax并允许用户输入新值吗?

时间:2016-12-12 01:20:53

标签: jquery select2 jquery-select2-4

am using select 2,效果很好。我有一个例子,用户通过ajax从下拉列表中选择(与链接中列出的远程数据示例完全相同)但我希望用户能够搜索以及能够键入一个新的值而不是&# 39; t存在于后端。

我有这个在多选中工作但是在使用单个下拉选项时试图查看是否有相同的支持?

3 个答案:

答案 0 :(得分:7)

根据我的理解,你想要的是使用single select框,用户可以从ajax源中选择,也可以自由输入文本。

此外,您已经有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;
}
&#13;
.select2-container {
  width: 100% !important;
}
&#13;
<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>
&#13;
&#13;
&#13;

所需的更改是。

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

添加此设置时,如果找不到匹配项,则插件的结果为enter image description here

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

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

有了这个,该插件能够从ajax和自由类型形式中选择值。这是一个选择的例子,因为这就是你想要的。

希望这有帮助!!

答案 1 :(得分:2)

以下是代码:

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

并从select2中删除多个属性。

我希望这会起作用

答案 2 :(得分:1)

  

以下是select2文档中的示例

&#13;
&#13;
$(".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
});
&#13;
&#13;
&#13;