javascript 将多个 Select2 链接在一起
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30244576/
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
Chaining multiple Select2 together
提问by I Test
Trying to make two chained auto populating select fields using select2 plugin The first select contains countries names(static select) and the second shows the states of the country selected from the first select my code is
尝试使用 select2 插件制作两个链接的自动填充选择字段第一个选择包含国家名称(静态选择),第二个显示从第一个选择中选择的国家的状态我的代码是
<select id="country" name="country" size="1" class=" form-control">
<option></option>
<option value="1">USA</option>
<option value="2">Untied Kingdom</option>
<option value="3">France</option>
etc........
</select>
<select id="states" name="states" size="1" class="form-control">
<option></option>
</select>
The JavaScript Code
JavaScript 代码
$(document).ready(function() {
$('#country').select2({
placeholder: 'Select Country',
allowClear: true
});
$('#state').select2({
placeholder: 'Select State',
allowClear: true
});
$('#country').change(function() {
var selectedCountries = $('#countryoption:selected').val();
var selectedCountries = 'id='+ selectedCountries;
$.ajax({
type: 'POST',
url: 'http://localhost/CodeIgniter/countries/get_state/',
dataType: 'html',
data: selectedCountries,
}).done( function( data ) {
data = $.map(data, function(item) {
return { id: item.id, text: item.name };
});
$('#state').select2({
data: data
});
}
})
});
});
The Returened Results in JSON
JSON 中的返回结果
{"id":"1","text":"Chigaco"}{"id":"4","text":"Albama"}{"id":"2","text":"Tulsa"} etc...........
I searched a lot for an example to help me with this but nothing working right all I need is to show the states of the country chosen in the first select and pass it to the second select known that I'm using select2 v4.0 and jquery v2
我搜索了很多示例来帮助我解决这个问题,但没有任何工作可以正常工作,我只需要显示在第一个选择中选择的国家/地区的州,并将其传递给第二个选择,我知道我正在使用 select2 v4.0 和jQuery v2
回答by Kevin Brown
A Select2 can be chained in the same way that a standard <select>
can be chained. So that means that when the value of the first select is chained, the second select is reset (generally to a placeholder) and the options generally change as well.
Select2 的链接方式<select>
与链接标准的方式相同。所以这意味着当第一个选择的值被链接时,第二个选择被重置(通常为占位符)并且选项通常也会改变。
You have two options for how this can be done with Select2:
对于如何使用 Select2 完成此操作,您有两种选择:
Pre-load the options for the second
<select>
when the value changes, and let Select2 handle searching locally. This would be similar to how you are currently trying to do it, but may suffer from issues when there are a large number of options that can be selected in the second<select>
.In your case, there shouldn't be thousands of "states" (for whatever degree of state) within a country, so local searching shouldn't be too much of an issue.
Use Select2's AJAX functionality and pass in a different parameter as the
url
to use based on the value of the first<select>
. This requires that you have a dynamic endpoint that can handle retrieving the items for the second select as well as filtering them when searching, so it's not always feasible.If you already have an endpoint like this that supports filtering, this is a more responsive option as the user doesn't have to necessarily wait for all options to be retrieved before they can select an option from the second
<select>
.
<select>
当值改变时预加载第二个选项,并让 Select2 处理本地搜索。这将类似于您当前尝试执行的操作,但是当在第二个<select>
.在您的情况下,一个国家内不应该有数千个“州”(无论州的程度如何),因此本地搜索不应该是一个太大的问题。
使用 Select2 的 AJAX 功能,并
url
根据第一个 的值传入不同的参数作为要使用的参数<select>
。这要求您有一个动态端点,可以处理为第二个选择检索项目以及在搜索时过滤它们,因此它并不总是可行的。如果您已经有一个像这样支持过滤的端点,这是一个响应更快的选项,因为用户不必等待所有选项都被检索到,然后他们才能从第二个
<select>
.
What option you choose largely depends on what you already have set up, the size of the data set that you are working with (Select2 does not handle well with thousands of options), and the user experience you want to provide.
您选择的选项在很大程度上取决于您已经设置的内容、您正在使用的数据集的大小(Select2 不能很好地处理数千个选项)以及您想要提供的用户体验。
The code for the first option would be similar to
第一个选项的代码类似于
$("#first").select2({
placeholder: 'Select a number range'
});
$("#second").select2({
placeholder: 'Select a number'
});
$("#first").on("change", function () {
$("#second option[value]").remove();
var newOptions = []; // the result of your JSON request
$("#second").append(newOptions).val("").trigger("change");
});
And can be tested at the following jsbin, using ranges of numbers instead of countries and states: http://jsbin.com/wigalivapi/1/edit?html,output
并且可以在以下 jsbin 进行测试,使用数字范围而不是国家和州:http://jsbin.com/wigalivapi/1/edit?html,output
Note that while this is similar to the code you were using, there are a few small difference that would have caught you.
请注意,虽然这与您使用的代码相似,但还是有一些细微的差别可能会引起您的注意。
You are setting
dataType: "html"
when you are really expectingdataType: "json"
. You are returning JSON in your response, not HTML.You are not clearing your
<select>
before you call.select2({data:[]})
a second time. Select2 doesn't automatically remove the<option>
tags it generates withdata
, so you need to do that on your own.When you change the value of the
<select>
, you never tell Select2 about it. You need to re-trigger thechange
event on the second<select>
after you change it.The JSON that you provide in your question does not appear to be valid. Now I'm not sure if that is just because you are giving it as an example, but I would check your JSON response with JSONLintjust to ensure that it is valid.
dataType: "html"
当您真正期待时,您正在设置dataType: "json"
。您在响应中返回 JSON,而不是 HTML。<select>
在您.select2({data:[]})
第二次打电话之前,您没有清除您的。Select2 不会自动删除<option>
它使用 生成的标签data
,因此您需要自己执行此操作。当您更改 的值时
<select>
,您永远不会告诉 Select2。更改后,您需要change
在第二次重新触发该事件<select>
。您在问题中提供的 JSON 似乎无效。现在我不确定这是否仅仅是因为您将其作为示例,但我会使用JSONLint检查您的 JSON 响应以确保它有效。
The code for the second option would be similar to
第二个选项的代码类似于
$("#first").select2({
placeholder: 'Select a number range'
});
$("#second").select2({
placeholder: 'Select a number',
ajax: {
url: http://localhost/CodeIgniter/countries/get_state/',
type: 'POST',
data: function (params) {
return {
id: $("#first").val(),
search: params.term
}
}
}
});
And this can be tested at the following jsbin, which mocks the response using a range of numbers (similar to the other example): http://jsbin.com/gihusohepe/1/edit?html,output
这可以在以下 jsbin 进行测试,它使用一系列数字模拟响应(类似于另一个示例):http://jsbin.com/gihusohepe/1/edit?html,output
回答by Pavan Kumar Jorrigala
you missed commas in json response.
你错过了 json 响应中的逗号。
http://jsfiddle.net/jEADR/1570/
http://jsfiddle.net/jEADR/1570/
var data = [{"id":"1","text":"Chigaco"},{"id":"4","text":"Albama"},{"id":"2","text":"Tulsa"}];
var data2=[];
$.map(data, function(item) {
data2.push( { id: item.id, text: item.text });
});
$('#state').select2({
data: data2
});