javascript Select2从属下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14797261/
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
Select2 Dependent dropdown lists
提问by Lee Baker
I am trying to use the Select2 plugin to have 4 dropdown lists that depend on each other. I have struggled to find the right way to update the data that loads the options in.
我正在尝试使用 Select2 插件来拥有 4 个相互依赖的下拉列表。我一直在努力寻找更新加载选项的数据的正确方法。
My goal is to load the new data via ajax, but once I have it in the client I am unable to add the new data to the select list.
我的目标是通过 ajax 加载新数据,但是一旦我在客户端中拥有它,我就无法将新数据添加到选择列表中。
The code I have tried is here:
我试过的代码在这里:
$(#"a3").select2({
placeholder: "select an item",
allowClear: true}).on("change",
function (e) {
var results = $.get("url?id=2",
function (data, textStatus, jqXHR) {
$(this).select2({ data: { results: data, text: "Name" } });
});
}
);
There is another question here select2 changing items dynamicallybut the solution there worked with Select2 v3.2 but not Select2 v3.3
这里还有另一个问题 select2 动态更改项目,但那里的解决方案适用于 Select2 v3.2 但不适用于 Select2 v3.3
采纳答案by Lee Baker
Igor has come back to me with a way to do this
伊戈尔已经回到我身边,有一种方法可以做到这一点
var data=[...];
$().select2({data: function() {return {results:data};}});
/// later
data=[...something else];
// next query select2 will use 'something else' data
回答by igor.vaynberg
The correct format is:
正确的格式是:
.select2("data", {...})
回答by Anis
For Select2 v4.x, here is a small js class.
对于 Select2 v4.x,这里是一个小的js 类。
Using this, options of a select2 list box will be loaded/refreshed by ajax based on selection of another select2 list box. And the dependency can be chained.
使用这个,一个 select2 列表框的选项将被 ajax 基于另一个 select2 列表框的选择加载/刷新。并且可以链接依赖项。
For example -
例如 -
new Select2Cascade($('#country'), $('#province'), 'path/to/geocode', {type:"province", parent_id: ''});
new Select2Cascade($('#province'), $('#district'), 'path/to/geocode', {type:"district", parent_id: ''});
Check the demo on codepen. Also here is a post on how to useit.