선택2에서 AJAX로 태그 지정
저는 select2로 태깅을 하고 있습니다.
select2의 요구사항은 다음과 같습니다.
- select2 ajax를 사용해서 태그를 검색해야 합니다.
- 또한 목록에 없는 값을 허용(Ajax 결과)하는 select2에서 "태그"를 사용해야 합니다.
두 시나리오는 독립적으로 작동합니다.그러나 joined 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
JSON 결과를 ajax 검색으로 반환하고 해당 용어가 아무런 결과를 반환하지 않는 경우 해당 용어에서 태그를 생성할 수 있도록 허용하는 보다 완벽한 답변은 다음과 같습니다.
$(".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 선택
몇 가지 개선된 예:
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-01-22:
수정 jsfiddle: http://jsfiddle.net/X6V2s/66/
업데이트 2015-09-09:
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}; }
이 옵션 항목을 추가하기
결과 목록의 첫 번째 결과로 검색어를 반환하도록 하여 이 작업을 수행할 수 있습니다.그런 다음 사용자는 해당 결과를 태그로 선택할 수 있습니다.
언급URL : https://stackoverflow.com/questions/14229768/tagging-with-ajax-in-select2
'codememo' 카테고리의 다른 글
| node.js 자식 프로세스 - 스폰과 포크의 차이 (0) | 2023.10.30 |
|---|---|
| 내 데이터를 필터링하는 방법은? (ng-grid) (0) | 2023.10.20 |
| JSR 303 Bean Validation + 자바스크립트 클라이언트측 Validation (0) | 2023.10.20 |
| 정적 클래스, 인터페이스 또는 xml 리소스 중에서 안드로이드에서 상수를 정의하는 가장 좋은 방법은 무엇입니까? (0) | 2023.10.20 |
| 각도 2 구성 요소 생성기 대 OnInit (0) | 2023.10.20 |