AJAX를 사용하는 jQuery Select2 컨트롤에 동적으로 항목 추가
AJAX를 사용하여 다음을 채우는 jQuery Select2 컨트롤이 있습니다.
<input type="text" name="select2" id="select2" style='width:400px' value="999">
var initialSelection = { id: '999', text:"Some initial option"};
$("#select2").select2({
placeholder: "Select Option",
minimumInputLength: 2,
ajax: {
url: "/servletToGetMyData",
dataType: 'json',
data: function (term, page) { return { term: term }; },
results: function (data, page) { return { results: data.results} }
},
initSelection : function(element, callback){ callback(initialSelection); },
escapeMarkup: function (m) { return m; }
});
AJAX는 가능한 옵션의 데이터베이스에 링크하기 위해 두 글자의 입력이 필요합니다.
문제는 대화상자가 데이터베이스에 존재하지 않는 경우 사용자가 대화상자를 사용하여 새 옵션을 추가할 수 있다는 것입니다.그 대화에서 돌아오면, 나는 다음과 같이 시도한다.
var o = $("<option/>", {value: newID, text: newText});
$('#select2').append(o);
$('#select2 option[value="' + newID + '"]').prop('selected',true);
$('#select2').trigger('change');
하지만 효과가 없어요.【AJAX Select 2】【AJAX Select 2】 여러 가지 요. 예를 들면$('#select2').select2("val", newID);
효과가 없어요.
2를 선택합니다. ★★★★★★★★★★★★★★.$('#select2').remove()
<input> Select 2 2 、 Select 2 、 Select 2 、 Select 2 。페이지에 두 개 이상의 Select2 컨트롤이 있기 때문에 Select2 컨트롤에 클래스 셀렉터를 사용할 수 없습니다.필요한 다른 컨트롤이 삭제되기 때문입니다.
a) AJAX를 사용하는 Select2 컨트롤에 옵션을 동적으로 추가하거나 b) Select2 컨트롤을 완전히 삭제하여 프로그래밍 방식으로 다시 추가할 수 있도록 하는 방법을 알고 계십니까?아니면 다른 해결책도...
편집 .select2("destroy")를 사용하여 select2 요소를 삭제하는 방법을 나타내는 다른 질문이 있습니다.이것은 효과가 있지만, 제 생각에는 차선책입니다.select2를 삭제하고 다시 작성하는 것보다 옵션을 추가하는 것이 훨씬 더 좋습니다.
2개의 v4를 선택해주세요. 만들 수 요.new Option
에 추가합니다.select
직접 요소.코드펜 또는 다음 예를 참조하십시오.
$(document).ready(function() {
$("#state").select2({
tags: true
});
$("#btn-add-state").on("click", function(){
var newStateVal = $("#new-state").val();
// Set the value, creating a new option if necessary
if ($("#state").find("option[value=" + newStateVal + "]").length) {
$("#state").val(newStateVal).trigger("change");
} else {
// Create the DOM option that is pre-selected by default
var newState = new Option(newStateVal, newStateVal, true, true);
// Append it to the select
$("#state").append(newState).trigger('change');
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<select id="state" class="js-example-basic-single" type="text" style="width:90%">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
<br>
<br>
<input id="new-state" type="text" />
<button type="button" id="btn-add-state">Set state value</button>
힌트: 텍스트 상자에 "AL" 또는 "WY"와 같은 기존 값을 입력해 보십시오.그런 다음 몇 가지 새로운 값을 추가해 보십시오.
이를 통해 다음과 같은 간단한 솔루션을 얻을 수 있었습니다.AJAX를 사용한 삽입 후 Select2에서 데이터 설정
$("#select2").select2('data', {id: newID, text: newText});
Select2 버전 4 이상의 경우
구문이 변경되어 다음과 같이 쓸 필요가 있습니다.
// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});
// clear and add new option
$("#select_with_data").html('').select2({data: [
{id: '', text: ''},
{id: '1', text: 'Facebook'},
{id: '2', text: 'Youtube'},
{id: '3', text: 'Instagram'},
{id: '4', text: 'Pinterest'}]});
// append option
$("#select_with_data").append('<option value="5">Twitter</option>');
$("#select_with_data").val('5');
$("#select_with_data").trigger('change');
Select2 4.0.2의 경우
$("#yourId").append("<option value='"+item+"' selected>"+item+"</option>");
$('#yourId').trigger('change');
이 링크(http://www.bootply.com/122726)를 사용하여 문제를 해결했습니다.너에게 도움이 되길 바란다
select2 jquery의 add 옵션을 지정하고 백엔드에서 새로운 옵션에 대해 작성된 링크 ID(#addNew)를 사용하여 Ajax 콜을 바인드합니다.및 코드
$.getScript('http://ivaynberg.github.io/select2/select2-3.4.5/select2.js',function(){
$("#mySel").select2({
width:'240px',
allowClear:true,
formatNoMatches: function(term) {
/* customize the no matches output */
return "<input class='form-control' id='newTerm' value='"+term+"'><a href='#' id='addNew' class='btn btn-default'>Create</a>"
}
})
.parent().find('.select2-with-searchbox').on('click','#addNew',function(){
/* add the new term */
var newTerm = $('#newTerm').val();
//alert('adding:'+newTerm);
$('<option>'+newTerm+'</option>').appendTo('#mySel');
$('#mySel').select2('val',newTerm); // select the new term
$("#mySel").select2('close'); // close the dropdown
})
});
<div class="container">
<h3>Select2 - Add new term when no search matches</h3>
<select id="mySel">
<option>One</option>
<option>Two</option>
<option>Three</option>
<option>Four</option>
<option>Five</option>
<option>Six</option>
<option>Twenty Four</option>
</select>
<br>
<br>
</div>
Bumpious Q Bangwhistle의 답변은 다음과 같습니다.
$('#select2').append($('<option>', {
value: item,
text : item
})).select2();
됩니다.<select>
태그를 지정하고 2를 선택하여 다시 표시합니다.
이렇게 했더니 신기하게 잘 되더라고요.
var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2,
text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
$(".js-example-data-array").select2({
data: data
})
$("#my_select").select2('destroy').empty().select2({data: [{id: 1, text: "new_item"}]});
동적 태깅을 에이잭스와 함께 사용하기 위해 제가 한 일은 다음과 같습니다.
버전 3.5를 2개 선택
이 기능은 버전 3.5에서는 간단합니다.createSearchChoice
훅. 여러 선택에도 사용할 수 있습니다.multiple: true
그리고.tags: true
설정되었습니다.
HTML
<input type="hidden" name="locations" value="Whistler, BC" />
JS
$('input[name="locations"]').select2({
tags: true,
multiple: true,
createSearchChoice: function(term, data) {
if (!data.length)
return { id: term, text: term };
},
ajax: {
url: '/api/v1.1/locations',
dataType: 'json'
}
});
여기서의 아이디어는 select2의createSearchChoice
두 분 다 지나가시는 후크term
사용자가 입력한 Ajax 응답(as.data
). ajax가 빈 목록을 반환하는 경우 select2에 사용자가 입력한 사용자에게 제공하도록 지시합니다.term
옵션으로서
데모: https://johnny.netlify.com/select2-examples/version3
버전 4를 2개 선택합니다.x
버전 4.X에는createSearchChoice
더 이상 훅을 걸지 않지만, 같은 일을 한 방법은 이렇습니다.
HTML
<select name="locations" multiple>
<option value="Whistler, BC" selected>Whistler, BC</option>
</select>
JS
$('select[name="locations"]').select2({
ajax: {
url: '/api/v1.1/locations',
dataType: 'json',
data: function(params) {
this.data('term', params.term);
return params;
},
processResults: function(data) {
if (data.length)
return {
results: data
};
else
return {
results: [{ id: this.$element.data('term'), text: this.$element.data('term') }]
};
}
}
});
아이디어에서는 사용자가 입력한 용어를 select2의 내 jQuery의 데이터스토어에 저장하는 것입니다.data
훅. 그리고 select2's에processResults
후크, Ajax 응답이 비어 있는지 확인합니다.이 경우 사용자가 입력한 저장된 용어를 가져와 옵션으로 반환하고 2를 선택합니다.
데모: https://johnny.netlify.com/select2-examples/version4
언급URL : https://stackoverflow.com/questions/25428361/dynamically-add-item-to-jquery-select2-control-that-uses-ajax
'programing' 카테고리의 다른 글
Oracle: 특정 범위에 걸쳐 "그룹화"하는 방법 (0) | 2023.03.14 |
---|---|
spring-web 용 스프링 부트 자동 설정을 방지하는 방법 (0) | 2023.03.14 |
리액트 네이티브는 왜 자신을 정당화하지 않는가? (0) | 2023.02.15 |
정의되지 않은 함수 wp_mail 호출 (0) | 2023.02.15 |
JSXtransformer의 TD 태그 몇 개를 올바르게 랩하는 방법 (0) | 2023.02.11 |