Select2:加载选定的值 [英] Select2: loading selected values
问题描述
我正在尝试从数据库中将选择的值加载到我的多重选择框中.
Im trying to load the selected values from the database into my multiple select box.
最初从数据库中加载选项时,它工作正常.
When I load the option initially from the database, It work perfect.
但是我想为此记录添加 SELECTED 项. 我已经尝试了几种方法,有点像这样.
But I would like to add the SELECTED items for this rrecord. I've tried a few approaches which is a bit hacky, like this.
var keywordArray = new Array();
keywordArray = test[0].keyword.split(",");
for( var x = 0; x < keywordArray.length ; x++){
foundKeyword = $( "select" ).find("option[value="+keywordArray[x]+"]").text();
$('.select2-choices').prepend("<li class='select2-search-choice'><div>" + foundKeyword + "</div><a href='#' class='select2-search-choice-close' tabindex='-1'></a></li>");
$('.select2-search-field input').attr("aria-activedescendant","select2-result-label-25");
$('.select2-search-field input').css("width", "10px");
$('.select2-search-field input').removeClass("select2-default");
}
此CANT的工作方式,而且无法正常工作
This CANT be how its done, and besides it does not work propperly
即使SELECTED关键字似乎在那里.您无法删除它们,并且下拉列表中的关联值仍然是可选的(不显示为灰色).
even though the SELECTED keywords appear to be there. You cant delete them and the associated value in the dropdown is still selectable (not greyed out).
我已经从网络上尝试了一个例子,但没有用
Ive tried a example from the net as-well, Which did not work
var pills = [{id:0, text: "ECHO"}, {id:1, text: "BRAVO"}];
$('#media_keywords').select2({
placeholder: "Select a pill",
data: function() { return {results: pills}; }
});
所以我的问题是,如何从数据库加载SELECTED数据并刷新或重新初始化select2
选定区域?这还需要禁用已经选择的项目的选择功能.
So my question is, how do you load the SELECTED data from the DB and refresh or re-initialise the select2
selected area? This also needs to disable the select capability of items already selected.
推荐答案
因此,在Mr Arun P Johny
的帮助下,
我终于得到了非常简单的答案.
So after a little help from Mr Arun P Johny
,
I finaly got to the very simple answer.
也许我还没有完全掌握它,但是我理解是正确的,您必须以不同的方式处理加载,具体取决于您是从input
还是select
创建Select2
.
Maybe I dont fully grasp it yet, but is I understand correctly, you have to approach the loading differently depending if you are creating your Select2
from a input
or a select
.
我的是通过选择创建的,因此从AJAX调用中获取数据,我只是简单地使用包含所选项目ID值的数组,并像这样通过它传递
Mine was created from a select so getting the data back from the AJAX call, I simply used the array containing the ID values of the selected items and passed it through like this
$('#media_keywords').select2().select2('val', keywordArray)
keywordArray
是ID的数组.
这篇关于Select2:加载选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!