선택 2 드롭 다운이지만 사용자가 새 값을 허용 하시겠습니까?
값 세트가있는 드롭 다운을 원하지만 사용자가 거기에 나열되지 않은 새 값을 "선택"할 수 있습니다.
그 참조 선택 2는 당신이 그것을 사용하는 경우이를 지원 tokens
모드 만 토큰을하지 않고 그것을 할 수있는 방법은 무엇입니까?
버전 4+의 경우 Kevin Brown의 아래 답변을 확인하십시오.
Select2 3.5.2 이하에서는 다음과 같은 것을 사용할 수 있습니다.
$(selector).select2({
minimumInputLength:1,
"ajax": {
data:function (term, page) {
return { term:term, page:page };
},
dataType:"json",
quietMillis:100,
results: function (data, page) {
return {results: data.results};
},
"url": url
},
id: function(object) {
return object.text;
},
//Allow manually entered text in drop down.
createSearchChoice:function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
});
(select2 메일 링리스트의 답변에서 가져 왔지만 지금 링크를 찾을 수 없습니다)
우수한 대답 에 의해 제공 @fmpwizard는 선택 2 3.5.2 이하 작동, 하지만 4.0.0에서 작동하지 않습니다 .
초창기 (이 질문만큼 빠르지는 않지만)부터 Select2는 "태깅"을 지원했습니다. 사용자가 허용하면 사용자가 자신의 가치를 더할 수 있습니다. 이 tags
옵션을 통해 활성화 할 수 있으며 documentation의 예제를 가지고 놀 수 있습니다 .
$("select").select2({
tags: true
});
기본적으로이 옵션은 입력 한 검색어와 동일한 텍스트를 가진 옵션을 만듭니다. 특별한 방식으로 표시하려는 경우 사용되는 객체를 수정하거나 선택한 객체를 원격으로 만들 수 있습니다.
$("select").select2({
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
}
});
select2:select
이벤트 를 통해 전달 된 객체에서 쉽게 찾을 수있는 플래그 역할을하는 것 외에도 extra 속성을 사용하면 결과에서 옵션을 약간 다르게 렌더링 할 수 있습니다. 따라서 " (신규) "를 그 옆 에 두어 새로운 옵션이라는 사실을 시각적으로 알리려면 다음과 같이하십시오.
$("select").select2({
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
$result.append(" <em>(new)</em>");
}
return $result;
}
});
코드를 유지하기 위해 @rrauenza Fiddle의 코드 를 그의 의견 에서 게시 하고 있습니다.
HTML
<input type='hidden' id='tags' style='width:300px'/>
jQuery
$("#tags").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0;
}).length===0)
{return {id:term, text:term};}
},
multiple: false,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
이러한 답변 중 많은 부분이 4.0 이상에서 작동하지 않으므로 ajax를 사용하는 경우 서버가 새로운 값을 옵션으로 추가하도록 할 수 있습니다. 따라서 다음과 같이 작동합니다.
- 사용자가 값을 검색합니다 (아약스가 서버에 요청 함)
- 값이 크면 옵션을 반환하십시오. 서버가 다음과 같이 해당 옵션을 추가하지 않은 경우 :
[{"text":" my NEW option)","id":"0"}]
- When the form is submitted just check to see if that option is in the db and if not create it before saving.
Improvent on @fmpwizard answer:
//Allow manually entered text in drop down.
createSearchChoice:function(term, data) {
if ( $(data).filter( function() {
return term.localeCompare(this.text)===0; //even if the this.text is undefined it works
}).length===0) {
return {id:term, text:term};
}
},
//solution to this error: Uncaught TypeError: Cannot read property 'localeCompare' of undefined
There is a better solution I think now
simply set tagging to true on the select options ?
tags: true
from https://select2.org/tagging
I just stumbled upon this from Kevin Brown. https://stackoverflow.com/a/30019966/112680
All you have to do for v4.0.6
is use tags: true
parameter.
var text = 'New York Mills';
var term = 'new york mills';
return text.localeCompare(term)===0;
In most cases we need to compare values with insensitive register. And this code will return false, which will lead to the creation of duplicate records in the database. Moreover String.prototype.localeCompare () is not supported by browser Safary and this code will not work in this browser;
return this.text.localeCompare(term)===0;
will better replace to
return this.text.toLowerCase() === term.toLowerCase();
Thanks for the help guys, I used the code below within Codeigniter I I am using version: 3.5.2 of select2.
var results = [];
var location_url = <?php echo json_encode(site_url('job/location')); ?>;
$('.location_select').select2({
ajax: {
url: location_url,
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
results = [];
$.each(data, function(index, item){
results.push({
id: item.location_id,
text: item.location_name
});
});
return {
results: results
};
}
},
//Allow manually entered text in drop down.
createSearchChoice:function(term, results) {
if ($(results).filter( function() {
return term.localeCompare(this.text)===0;
}).length===0) {
return {id:term, text:term + ' [New]'};
}
},
});
참고URL : https://stackoverflow.com/questions/14577014/select2-dropdown-but-allow-new-values-by-user
'Programing' 카테고리의 다른 글
요소 외부의 클릭 이벤트에서 요소를 숨기려면 어떻게합니까? (0) | 2020.07.21 |
---|---|
jquery 가로 드되었는지 확인한 다음 false이면로드하십시오. (0) | 2020.07.21 |
MAC 주소의 정규식은 무엇입니까? (0) | 2020.07.21 |
그룹의 어떤 라디오 버튼이 점검됩니까? (0) | 2020.07.21 |
$ _REQUEST []를 사용하는 데 무엇이 문제입니까? (0) | 2020.07.21 |