Nested Select2 with AJAX dependent call

I am using Select2 with jQuery to create a dependent relationship between SELECT elements in a form. I am trying to build a typical relationship: a country has states, states have cities, a city is a city, etc. Now I am doing this:

$(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" two or more times, I got this error:

uncaught exception: request function not defined for Select2 s2id_municipio

Note. I changed "Estado" more than once to get this error if you try to reproduce the same error

Maybe a mistake in my logic, or maybe not. I need help here, and my question is: is it possible to build a nested dependent SELECT (using Select2, of course), with AJAX calls to build the same structure?

You can see an example of life in this link, choose any option, for example, “Persona Natural”, then in “Datos Personales” on “Pais de Residencia” choose “Venezuela” and then try to change the “Estado” field two or more times and see What will happen, any tips on this?

PS: Sorry for the Spanish language in some parts, this is a job for the Spanish client, and he hates English (don't ask me why)

+1
source share
2 answers

You really should use the Select2 AJAX function instead of doing it yourself. This means changing the base elements from <select> to <input type="hidden" /> and indicating Select2 in the data source.

https://ivaynberg.imtqy.com/select2/#ajax

Here is an example of how to reset states.

 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 use $("input.estados") for the selector, and not just for the class. This is because Select2 will copy the class to the Select2 container, and this will cause problems when accessing it again when you get multiple items. This is explained a little more in this answer .

+1
source

This gist is an easy-to-use JS class for selecting dependent blocks of a Select2 list. For instance -

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

Check out the demo on codepen . There is also a message on how to use it.

0
source

Source: https://habr.com/ru/post/1238898/


All Articles