Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

javascript - Tagging with AJAX in select2

I am doing tagging with select2

I have these requirements with select2:

  1. I need to search some tags using select2 ajax
  2. Also I need to use "tags" in select2 which Allows values that are not in the list(Ajax result).

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...