【问题标题】:Select2 tagging: add custom text behind new tagSelect2 标记:在新标记后面添加自定义文本
【发布时间】:2021-02-07 01:37:08
【问题描述】:

我正在使用select2 tagging feature。有没有一种简单的方法可以在新标签后面添加自定义文本。我的意图是,用户知道他/她会添加标签。

结果应该是这样的,例如。在颜色名称的例子中,它可以在新标签之后说“新颜色”:

$(".js-example-tags").select2({
  tags: true
});
select, pre {
  display: inline-block;
}

.js-example-tags {
  width: 256px;
}
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<select class="js-example-tags">
  <option selected="selected">orange</option>
  <option>white</option>
  <option>purple</option>
</select> <pre><== Type new tag into search and click enter</pre>

【问题讨论】:

  • 你在文档中检查过这个吗? select2.org/tagging#tag-properties
  • 您的示例未显示如何从您的选择中添加新标签
  • @Frenchy 只需输入一种新颜色并按回车键或单击它的选择列表。由于这不是很直观,我想添加一些文本,例如。 “添加新颜色”...

标签: jquery jquery-select2 tagging


【解决方案1】:

如果我理解你的逻辑,你可以试试这个:

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

function newtag(params, data){
    var term = $.trim(params.term);
    if (term === '') {
      return null;
    }
      return {
      id: term,
      text: term + " (New color)",
      newTag: true // add additional parameters
    }
}

function matchCustom(params, data) {
    // If there are no search terms, return all of the data
    if ($.trim(params.term) === '') {
      return data;
    }

    // Do not display the item if there is no 'text' property
    if (typeof data.text === 'undefined') {
      return null;
    }
    
   // Return `null` if the term should not be displayed
    return null;
}
select, pre {
  display: inline-block;
}

.js-example-tags {
  width: 256px;
}
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<select class="js-example-tags">
  <option selected="selected">orange</option>
  <option>white</option>
  <option>purple</option>

</select> <pre><== Type new tag into search and click enter</pre>

【讨论】:

  • 唯一的改进是所选标签不再显示“新颜色”。我的目的是让用户清楚地知道,他必须选择新标签(通过按 Enter 或单击它)。
  • 你的意思是你不想(新颜色)添加后的未来选择?
猜你喜欢
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
  • 2016-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多