在select2中使用AJAX标记 [英] Tagging with AJAX in select2

查看:75
本文介绍了在select2中使用AJAX标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 select2

我对select2有这些要求:

I have these requirements with select2:

  1. 我需要使用select2 ajax搜索一些标签
  2. 我还需要在select2中使用标签",以允许列表中未包含的值(Ajax结果).

这两种方案都是独立工作的.但是仅将aJax值连接在一起.如果我们键入列表中未包含的其他任何值,则会显示未找到匹配项"

Both the scenarios work independently. But joined together aJax values are only populated. If we type any other values not in the list then it says "no matches found"

我的情况如果用户键入列表中没有的任何新值,请允许他们组成自己的标签.

My scenario If user type any new value which is not in the list, allow them to make up their own tag.

任何使这项工作可行的方法吗?

Any way to make this work?

推荐答案

Select2具有函数"createSearchChoice":

Select2 has the function "createSearchChoice":

根据用户的搜索词创建一个新的可选选项.允许 无法通过查询功能创建选项.有用的时候 用户可以即时创建选择,例如针对标记"用例.

Creates a new selectable choice from user's search term. Allows creation of choices not available via the query function. Useful when the user can create choices on the fly, eg for the 'tagging' usecase.

您可以使用以下方法实现您想要的:

You could achieve what you want by using:

createSearchChoice:function(term, data) {
  if ($(data).filter(function() {
    return this.text.localeCompare(term)===0;
  }).length===0) {
    return {id:term, text:term};
  }
},
multiple: true

这是一个更完整的答案,可以将JSON结果返回给ajax搜索,并允许从该术语创建标签(如果该术语未返回任何结果):

Here's a more complete answer that returns a JSON result to an ajax search, and allows tags to be created from the term, if the term returned no results:

$(".select2").select2({
  tags: true,
  tokenSeparators: [",", " "],
  createSearchChoice: function(term, data) {
    if ($(data).filter(function() {
      return this.text.localeCompare(term) === 0;
    }).length === 0) {
      return {
        id: term,
        text: term
      };
    }
  },
  multiple: true,
  ajax: {
    url: '/path/to/results.json',
    dataType: "json",
    data: function(term, page) {
      return {
        q: term
      };
    },
    results: function(data, page) {
      return {
        results: data
      };
    }
  }
});

这篇关于在select2中使用AJAX标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆