简体   繁体   English

带相关AJAX调用的嵌套Select2

[英]Nested Select2 with dependent AJAX call

I'm using Select2 with jQuery to build a dependent relationship between SELECT elements on a form. 我将Select2与jQuery结合使用,以在表单上的SELECT元素之间建立依赖关系。 I'm trying to build the typically relation: Country has States, States has Cities, City has Town and so on. 我正在尝试建立一种典型的关系:国家有州,国家有城市,城市有镇等等。 Right now I'm doing in this way: 现在,我正在按照这种方式进行操作:

$(document).ready(function() {
    $(".pais").on('change', function() {
        pais = $(this).find('option:selected').val();
        $.get(Routing.generate('estados', {pais_id: pais})).success(function(data) {
            if (data.message === "") {
                $('.estado').empty().append('<option value="-1">Seleccione un estado</option>');
                $.each(data.entities, function(i, d) {
                    $('.estado').append('<option value="' + d.id + '">' + d.nombre + '</option>');
                });

                $('.estado').removeAttr('disabled');
                $('.estado').next('span').remove();
                $('.estado').closest('.form-group').removeClass('has-error');
                $('.estado').select2();
            } else {
                $('.estado').next('span').remove();
                $('.estado').closest('.form-group').addClass('has-error');
                $('.estado').after('<span class="help-block">' + data.message + '</span>');

                $('.estado').empty().append('<option value="-1">Seleccione un estado</option>').attr('disabled', 'disabled');
                $('.municipio').empty().append('<option value="-1">Seleccione un municipio</option>').attr('disabled', 'disabled');
                $('.ciudad').empty().append('<option value="-1">Seleccione un ciudad</option>').attr('disabled', 'disabled');
                $('.parroquia').empty().append('<option value="-1">Seleccione un parroquia</option>').attr('disabled', 'disabled');
            }
        }).error(function(data, status, headers, config) {
            if (status == '500') {
                message = "No hay conexión con el servidor";
            }
        });
    });

    $(".estado").change(function() {
        estado = $(this).find('option:selected').val();

        $.get(Routing.generate('municipios', {estado_id: estado})).success(function(data) {
            ...
        }).error(function(data, status, headers, config) {
            ...
        });

        $.get(Routing.generate('ciudades', {estado_id: estado})).success(function(data) {
            ...
        }).error(function(data, status, headers, config) {
            ...
        });
    });

    $(".municipio").change(function() {
        municipio = $(this).find('option:selected').val();

        $.get(Routing.generate('parroquias', {municipio_id: estado})).success(function(data) {
            ...
        }).error(function(data, status, headers, config) {
            ...
        });
    });
});

But when I change the same SELECT "Estado" or "Ciudad" or "Municipio" or "Parroquia" twice or more times I got this error: 但是,当我两次或更多次更改同一个SELECT“ Estado”或“ Ciudad”或“ Municipio”或“ Parroquia”时,出现此错误:

uncaught exception: query function not defined for Select2 s2id_municipio 未捕获的异常:未为Select2 s2id_municipio定义查询功能

Note: I changed "Estado" more than one time to get this error in case you can try to reproduce the same error 注意:我多次更改“ Estado”来获取此错误,以防您可以尝试重现相同的错误

Maybe the error is in my logic or maybe not so I need some help here and my question is: it's possible to build nested dependent SELECT (applying Select2 of course) with AJAX calls for build the same structure? 也许错误是我的逻辑,也许不是,所以我在这里需要一些帮助,我的问题是:可以使用AJAX调用来构建嵌套的依赖SELECT(当然应用Select2)以构建相同的结构吗?

You can take a look to live example in this link choose any option for example "Persona Natural" and then at "Datos Personales" at "Pais de Residencia" choose "Venezuela" and then try to change the "Estado" field two or more times and see what's happen, any advice on this? 您可以在此链接中查看实时示例,选择任何选项,例如“ Persona Natural”,然后在“ Pais de Residencia”的“ Datos Personales”中选择“委内瑞拉”,然后尝试将“ Estado”字段更改为两个或多个时代,看看发生了什么,对此有何建议?

PS: Sorry for Spanish language on some parts this is a job for a Spanish client and he hates English (don't ask me why) PS:对某些语言的西班牙语很抱歉,这是西班牙客户的工作,他讨厌英语(不要问我为什么)

You should really be using Select2's AJAX functionality instead of doing it on your own. 您应该真正使用Select2的AJAX功能,而不是自己做。 This means changing the underlying elements from <select> to <input type="hidden" /> and pointing Select2 at your data source. 这意味着将基础元素从<select>更改为<input type="hidden" />并将Select2指向您的数据源。

https://ivaynberg.github.io/select2/#ajax https://ivaynberg.github.io/select2/#ajax

Here is an example of how to convert the states drop down. 这是一个如何转换下拉状态的示例。

var $pais = $("select.pais");
var $estados = $("input.estados");

$estados.select2({
    placeholder: "Seleccione un estado",
    ajax: {
        url: function () {
            var pais = $pais.val();
            return Routing.generate('estados', {pais_id: pais});
        },
        results: function (data) {
            return {
                results: data.entities
            };
        }
    },
    formatNoResults: function () {
        return "No se encontraron estados para el país actual";
    }
    formatAjaxError: function () {
        return "No hay conexión con el servidor";
    }
}).select2("enable", false);

Note that I am using $("input.estados") for the selector instead of just the class. 请注意,我使用$("input.estados")作为选择器,而不仅仅是类。 This is because Select2 will copy the class to the Select2 container, and that will cause problems when referencing it again as you get multiple elements. 这是因为Select2会将类复制到Select2容器,并且当您获得多个元素时再次引用它会导致问题。 This is explained a little more in this answer . 这个答案对此进行了更多解释。

This gist is an easy to use JS class for making Select2 list boxes dependent. 要点是一个易于使用的JS类,用于使Select2列表框相关。 For example - 例如 -

new Select2Cascade($('#parent'), $('#child'), '/api/to/load/:parentId:/childs');

Check the demo on codepen . 查看codepen上的演示。 Also here is a post on how to use it. 另外这里是关于如何使用它的帖子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM