将项目动态添加到使用 AJAX 的 jQuery Select2 控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25428361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically add item to jQuery Select2 control that uses AJAX
提问by Bumptious Q Bangwhistle
I have a jQuery Select2 control that uses AJAX to populate:
我有一个使用 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; }
});
The AJAX links to a database of possible options and as you can see requires two characters of input.
AJAX 链接到可能选项的数据库,如您所见,需要两个字符的输入。
The problem is the user can use a dialog to add a new option if the option doesn't exist in the database. Upon return from that dialog, I try:
问题是如果数据库中不存在选项,用户可以使用对话框添加新选项。从该对话框返回后,我尝试:
var o = $("<option/>", {value: newID, text: newText});
$('#select2').append(o);
$('#select2 option[value="' + newID + '"]').prop('selected',true);
$('#select2').trigger('change');
But it doesn't work. The same exact code works for non-AJAX Select2 boxes. I've tried various alternatives, like using $('#select2').select2("val", newID);
but it doesn't work.
但它不起作用。相同的代码适用于非 AJAX Select2 框。我尝试了各种替代方案,例如使用,$('#select2').select2("val", newID);
但它不起作用。
I've even tried completely deleting the Select2 control. However, $('#select2').remove()
only removes the original <input> field but leaves the Select2 control lingering around. Note that the page has more than one Select2 control, so I can't use a class selector for Select2 controls as it will remove other controls that I need.
我什至尝试过完全删除 Select2 控件。但是,$('#select2').remove()
只删除了原始的 <input> 字段,而留下 Select2 控件挥之不去。请注意,该页面有多个 Select2 控件,因此我不能为 Select2 控件使用类选择器,因为它会删除我需要的其他控件。
Any idea how to either a) dynamically add an option to a Select2 control that uses AJAX; or b) completely delete a Select2 control so that it can be programmatically added back? Or any other solution...
知道如何 a) 向使用 AJAX 的 Select2 控件动态添加选项;或 b) 完全删除 Select2 控件,以便可以通过编程方式将其添加回来?或任何其他解决方案...
EditI found another question that shows how to remove a select2 element, using .select2("destroy"). This works but is, in my opinion, sub-optimal. I would much prefer to be able to just add the option than to destroy and re-create the select2.
编辑我发现了另一个问题,显示了如何使用 .select2("destroy") 删除 select2 元素。这有效,但在我看来,这是次优的。我更希望能够只添加选项而不是销毁并重新创建 select2。
采纳答案by Bumptious Q Bangwhistle
This provided a simple solution: Set data in Select2 after insert with AJAX
这提供了一个简单的解决方案: 在使用 AJAX 插入后在 Select2 中设置数据
$("#select2").select2('data', {id: newID, text: newText});
回答by alexw
This is a lot easier to do starting in select2 v4. You can create a new Option
, and append it to the select
element directly. See my codepenor the example below:
从 select2 v4 开始,这要容易得多。您可以创建一个new Option
,并将其select
直接附加到元素。请参阅我的codepen或下面的示例:
$(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>
Hint: try entering existing values into the text box, like "AL" or "WY". Then try adding some new values.
提示:尝试在文本框中输入现有值,例如“AL”或“WY”。然后尝试添加一些新值。
回答by Sruit A.Suk
In case of Select2 Version 4+
在 Select2 版本 4+ 的情况下
it has changed syntax and you need to write like this:
它改变了语法,你需要这样写:
// 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');
回答by Digvijay
In Select2 4.0.2
在 Select2 4.0.2 中
$("#yourId").append("<option value='"+item+"' selected>"+item+"</option>");
$('#yourId').trigger('change');
回答by Suneel
I have resolved issue with the help of this link http://www.bootply.com/122726. hopefully will help you
我在此链接http://www.bootply.com/122726的帮助下解决了问题 。希望能帮到你
Add option in select2 jquery and bind your ajax call with created link id(#addNew) for new option from backend. and the code
在 select2 jquery 中添加选项,并将您的 ajax 调用与后端的新选项创建的链接 id(#addNew) 绑定。和代码
$.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>
回答by hareluya86
Extending on Bumptious Q Bangwhistle's answer:
扩展 Bumptious Q Bangwhistle 的回答:
$('#select2').append($('<option>', {
value: item,
text : item
})).select2();
This would add the new options into the <select>
tags and lets select2 re-render it.
这会将新选项添加到<select>
标签中,并让 select2 重新渲染它。
回答by Musznik
$("#my_select").select2('destroy').empty().select2({data: [{id: 1, text: "new_item"}]});
回答by Chaudhry Waqas
I did it this way and it worked for me like a charm.
我是这样做的,它对我很有用。
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
})
回答by Johnny Oshika
To get dynamic tagging to work with ajax, here's what I did.
为了让动态标记与 ajax 一起工作,这就是我所做的。
Select2 version 3.5
Select2 版本 3.5
This is easy in version 3.5 because it offers the createSearchChoice
hook. It even works for multiple select, as long as multiple: true
and tags: true
are set.
这在 3.5 版中很容易,因为它提供了createSearchChoice
钩子。它甚至适用于多选,只要multiple: true
和tags: true
被设置。
HTML
HTML
<input type="hidden" name="locations" value="Whistler, BC" />
JS
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'
}
});
The idea here is to use select2's createSearchChoice
hook which passes you both the term
that the user entered and the ajax response (as data
). If ajax returns an empty list, then tell select2 to offer the user-entered term
as an option.
这里的想法是使用 select2 的createSearchChoice
钩子,它同时传递term
用户输入和 ajax 响应(作为data
)。如果 ajax 返回一个空列表,则告诉 select2 提供用户输入term
的选项。
Demo: https://johnny.netlify.com/select2-examples/version3
演示:https: //johnny.netlify.com/select2-examples/version3
Select2 version 4.X
Select2 版本 4.X
Version 4.X doesn't have a createSearchChoice
hook anymore, but here's how I did the same thing.
版本 4.X 不再有createSearchChoice
钩子了,但这是我做同样事情的方式。
HTML
HTML
<select name="locations" multiple>
<option value="Whistler, BC" selected>Whistler, BC</option>
</select>
JS
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') }]
};
}
}
});
The ideas is to stash the term that the user typed into jQuery's data store inside select2's data
hook. Then in select2's processResults
hook, I check if the ajax response is empty. If it is, I grab the stashed term that the user typed and return it as an option to select2.
想法是将用户输入到 jQuery 数据存储中的术语隐藏在 select2 的data
钩子中。然后在 select2 的processResults
钩子中,我检查 ajax 响应是否为空。如果是,我会获取用户输入的隐藏术语并将其作为选项返回给 select2。