将多个Select2链接在一起 [英] Chaining multiple Select2 together

查看:139
本文介绍了将多个Select2链接在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用select2插件制作两个链式自动填充选择字段
第一个选择包含国家/地区名称(静态选择),第二个选择显示从第一个选择我的代码中选择的国家/地区的状态

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

<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>

JavaScript代码

The JavaScript Code

$(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
                        });
                }
            })
    });
});

JSON中的退回结果

The Returened Results in JSON

{"id":"1","text":"Chigaco"}{"id":"4","text":"Albama"}{"id":"2","text":"Tulsa"} etc...........

我搜索了一个例子来帮助我这个,但没有任何正常工作我需要的是显示在第一个选择中选择的国家的状态并将其传递给第二个选择已知我正在使用select2 v4.0和jquery v2

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的链接方式与标准< select> <相同/ code>可以链接。这意味着当第一个选择的值被链接时,第二个选择被重置(通常是一个占位符),选项通常也会改变。

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完成此操作的两个选项:

You have two options for how this can be done with Select2:


  1. 预加载第二个的选项< select> 当值发生变化时,让Select2处理本地搜索。这与您当前尝试执行此操作的方式类似,但在第二个< select> 。

  1. 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.

使用Select2的AJAX功能,并将 url 传递给另一个参数根据第一个< select> 的值使用。这要求您有一个动态端点,可以处理第二个选择的项目,并在搜索时过滤它们,因此并不总是可行。

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.

如果您已经有一个支持过滤的端点,这是一个响应更快的选项,因为用户不必等待所有选项被检索,然后才能从第二个<$ c中选择一个选项$ c>< select>

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>.

您选择的选项在很大程度上取决于什么您已经设置了,您正在使用的数据集的大小(Select2不能很好地处理数千个选项),以及您想要提供的用户体验。

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.

第一个选项的代码类似于

$("#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");
});

并且可以在以下jsbin上测试,使用数字范围而不是国家和州: http://jsbin.com/wigalivapi/1/edit?html,output

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

请注意,虽然这与您使用的代码类似,但是会有一些小的差异会引起您的注意。

Note that while this is similar to the code you were using, there are a few small difference that would have caught you.


  1. 当你真的期待<$ c $时,你正在设置 dataType:html c> dataType:json。您在回复中返回JSON,而不是HTML。

  1. You are setting dataType: "html" when you are really expecting dataType: "json". You are returning JSON in your response, not HTML.

您没有清除< select> 再次拨打 .select2({data:[]})之前。 Select2不会自动删除它使用 data 生成的< option> 标记,因此您需要执行此操作您自己。

You are not clearing your <select> before you call .select2({data:[]}) a second time. Select2 doesn't automatically remove the <option> tags it generates with data, so you need to do that on your own.

当您更改< select> 的值时,您永远不会告诉Select2关于它。更改后,您需要在第二个< select> 上重新触发更改事件。

When you change the value of the <select>, you never tell Select2 about it. You need to re-trigger the change event on the second <select> after you change it.

您在问题中提供的JSON似乎无效。现在我不确定这是否只是因为你给它作为一个例子,但我会用 JSONLint检查你的JSON响应只是为了确保它有效。

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 JSONLint just to ensure that it is valid.

第二个选项的代码类似于

$("#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
      }
    }
  }
});

这可以在以下jsbin上测试,jsbin使用一系列数字来模拟响应(类似到另一个例子): http://jsbin.com/gihusohepe/1/edit?html ,输出

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

这篇关于将多个Select2链接在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆