Dynamically add item to jQuery Select2 control that uses AJAX
我有一个使用AJAX填充的jQuery Select2控件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <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链接到可能选项的数据库,如您所见,需要输入两个字符。
问题是,如果数据库中不存在选项,则用户可以使用对话框来添加新选项。从该对话框返回后,我尝试:
1 2 3 4 | var o = $("<option/>", {value: newID, text: newText}); $('#select2').append(o); $('#select2 option[value="' + newID + '"]').prop('selected',true); $('#select2').trigger('change'); |
但这是行不通的。相同的确切代码适用于非AJAX Select2盒。我尝试了各种替代方法,例如使用
我什至尝试完全删除Select2控件。但是,
任何想法如何:a)向使用AJAX的Select2控件动态添加选项;或b)完全删除Select2控件,以便可以以编程方式添加回它?或任何其他解决方案...
编辑
我发现了另一个问题,该问题显示了如何使用.select2(" destroy")删除select2元素。这有效,但我认为次优。我更希望能够仅添加选项,而不是销毁并重新创建select2。
从select2 v4开始,这要容易得多。您可以创建一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $(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'); } }); }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <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 src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"> <select id="state" class="js-example-basic-single" type="text" style="width:90%"> <option value="AL">Alabama</option> <option value="WY">Wyoming</option> </select> <input id="new-state" type="text" /> <button type="button" id="btn-add-state">Set state value</button> |
提示:尝试在文本框中输入现有值,例如" AL"或" WY"。然后尝试添加一些新值。
这提供了一个简单的解决方案:
用AJAX插入后在Select2中设置数据
1 | $("#select2").select2('data', {id: newID, text: newText}); |
如果是Select2版本4+
它已经更改了语法,您需要这样编写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // 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中
1 2 | $("#yourId").append("<option value='"+item+"' selected>"+item+"</option>"); $('#yourId').trigger('change'); |
我已通过此链接http://www.bootply.com/122726解决了问题。希望能对你有帮助
在select2 jquery中添加选项,并将您的ajax调用与创建的链接id(#addNew)绑定,以从后端获取新选项。
和代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | $.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+"'>Create" } }) .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 }) }); Select2 - Add new term when no search matches <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> |
扩展了Q Bangwhistle的答案:
1 2 3 4 | $('#select2').append($('<option>', { value: item, text : item })).select2(); |
这会将新选项添加??到
我是这样做的,它对我来说就像一种魅力。
1 2 3 4 5 6 7 | 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 }) |
1 | $("#my_select").select2('destroy').empty().select2({data: [{id: 1, text:"new_item"}]}); |
为了使动态标记能够与Ajax一起使用,这就是我所做的。
Select2版本3.5
在3.5版中,这很容易,因为它提供了
的HTML
1 | <input type="hidden" name="locations" value="Whistler, BC" /> |
JS
1 2 3 4 5 6 7 8 9 10 11 12 | $('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的
演示:https://johnny.netlify.com/select2-examples/version3
Select2版本4.X
版本4.X不再具有
的HTML
1 2 3 | <select name="locations" multiple> <option value="Whistler, BC" selected>Whistler, BC</option> </select> |
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $('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的
演示:https://johnny.netlify.com/select2-examples/version4