programing

select2에서 AJAX로 태그 지정

nasanasas 2020. 11. 1. 18:11
반응형

select2에서 AJAX로 태그 지정


select2로 태그 지정 중입니다.

select2에는 다음과 같은 요구 사항이 있습니다.

  1. select2 ajax를 사용하여 일부 태그를 검색해야합니다.
  2. 또한 목록에없는 값 (Ajax 결과)을 허용하는 select2에서 "태그"를 사용해야합니다.

두 시나리오 모두 독립적으로 작동합니다. 그러나 함께 결합 된 aJax 값은 채워집니다. 목록에없는 다른 값을 입력하면 "일치하는 항목이 없습니다"라고 표시됩니다.

내 시나리오 사용자가 목록에없는 새 값을 입력하면 자신의 태그를 만들 수 있습니다.

이 작업을 수행 할 방법이 있습니까?


Select2에는 "createSearchChoice"기능이 있습니다.

사용자의 검색어에서 선택 가능한 새로운 선택 항목을 만듭니다. 쿼리 기능을 통해 사용할 수없는 선택 항목을 만들 수 있습니다. 사용자가 즉석에서 선택 사항을 생성 할 수있는 경우에 유용합니다 (예 : '태그 지정'사용 사례).

다음을 사용하여 원하는 것을 얻을 수 있습니다.

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

다음은 ajax 검색에 JSON 결과를 반환하고 용어가 결과를 반환하지 않은 경우 용어에서 태그를 생성 할 수 있도록하는보다 완전한 답변입니다.

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

v4 선택

http://jsfiddle.net/8qL47c1x/2/

HTML :

<select multiple="multiple" class="form-control" id="tags" style="width: 400px;">
    <option value="tag1">tag1</option>
    <option value="tag2">tag2</option>
</select>

자바 스크립트 :

$('#tags').select2({
    tags: true,
    tokenSeparators: [','],
    ajax: {
        url: 'https://api.myjson.com/bins/444cr',
        dataType: 'json',
        processResults: function(data) {
          return {
            results: data
          }
        }
    },

    // Some nice improvements:

    // max tags is 3
    maximumSelectionLength: 3,

    // add "(new tag)" for new tags
    createTag: function (params) {
      var term = $.trim(params.term);

      if (term === '') {
        return null;
      }

      return {
        id: term,
        text: term + ' (new tag)'
      };
    },
});

v3.5.2 선택

몇 가지 개선 된 예 :

http://jsfiddle.net/X6V2s/66/

html :

<input type="hidden" id="tags" value="tag1,tag2" style="width: 400px;">

js :

$('#tags').select2({
    tags: true,
    tokenSeparators: [','],
    createSearchChoice: function (term) {
        return {
            id: $.trim(term),
            text: $.trim(term) + ' (new tag)'
        };
    },
    ajax: {
        url: 'https://api.myjson.com/bins/444cr',
        dataType: 'json',
        data: function(term, page) {
            return {
                q: term
            };
        },
        results: function(data, page) {
            return {
                results: data
            };
        }
    },

    // Take default tags from the input value
    initSelection: function (element, callback) {
        var data = [];

        function splitVal(string, separator) {
            var val, i, l;
            if (string === null || string.length < 1) return [];
            val = string.split(separator);
            for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
            return val;
        }

        $(splitVal(element.val(), ",")).each(function () {
            data.push({
                id: this,
                text: this
            });
        });

        callback(data);
    },

    // Some nice improvements:

    // max tags is 3
    maximumSelectionSize: 3,

    // override message for max tags
    formatSelectionTooBig: function (limit) {
        return "Max tags is only " + limit;
    }
});

JSON :

[
  {
    "id": "tag1",
    "text": "tag1"
  },
  {
    "id": "tag2",
    "text": "tag2"
  },
  {
    "id": "tag3",
    "text": "tag3"
  },
  {
    "id": "tag4",
    "text": "tag4"
  }
]

2015 년 1 월 22 일 업데이트 :

jsfiddle 수정 : http://jsfiddle.net/X6V2s/66/

2015 년 9 월 9 일 업데이트 :

Select2 v4.0.0 +에서는 더 쉬워졌습니다.

v4.0.0 선택

https://jsfiddle.net/59Lbxvyc/

HTML :

<select class="tags-select" multiple="multiple" style="width: 300px;">
  <option value="tag1" selected="selected">tag1</option>
  <option value="tag2" selected="selected">tag2</option>
</select>

JS :

$(".tags-select").select2({
  // enable tagging
  tags: true,

  // loading remote data
  // see https://select2.github.io/options.html#ajax
  ajax: {
    url: "https://api.myjson.com/bins/444cr",
    processResults: function (data, page) {
      return {
        results: data
      };
    }
  }
});

createSearchChoice : function (term) { return {id: term, text: term}; }

이 옵션 항목을 추가하십시오.


ajax 함수가 결과 목록의 첫 번째 결과로 검색어를 반환하도록하여이 작업을 수행 할 수 있습니다. 그런 다음 사용자는 해당 결과를 태그로 선택할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/14229768/tagging-with-ajax-in-select2

반응형