首页 > 解决方案 > 如何使用自定义输入填充 select2

问题描述

我实现了一个select2下拉菜单,允许用户输入自定义输入...

$("#select").select2({
  createSearchChoice:function(term, data) {
    if ($(data).filter(function() {
      return this.text.localeCompare(term)===0;
    }).length===0)
    {return {id:term, text:term};}
  },
  multiple: false,
  selectOnBlur: true,
  data: [{id: 1, text: '1'}, {id: 2, text: '2'}, {id: 3, text: '3'}]
});

这很好用,但是在某些情况下,我需要以编程方式为select2下拉菜单设置自定义值。我尝试执行以下操作...

// Doesn't work
$('#select').val('val', custom);

// Doesn't work
$('#select').val(custom);

有没有办法做到这一点?

我的选择下拉列表的工作小提琴

标签: javascriptjqueryjquery-select2

解决方案


我发现了如何完成我想要的。解决方案是...

$('#select').select2('data', {id: id, text: custom});

以下将输入设置为任何值custom而不添加到列表本身。

这是一个工作小提琴


推荐阅读