abonive
abonive

Reputation: 69

Ajax DropDown Populating based on previous dropdowns

i have a little problem with my js/ajax script. I'm learning js and my knowledge is basic at the moment.

I have a couple select dropdown populated by ajax and each depends on data from previous select dropdown.

  1. "Provincia" -> The Main Select Dropdown
  2. "Zona" -> Second Select - Depends on data from "Provincia"
  3. "Municipio" -> Third Select -> Depends on data from "Zona"
  4. "Barrio" -> Last Select -> Depends on data from "Municipio"

They work fine when selected manually. But I'm trying to make the stay selected when submitted the form. The data send using GET.

I'm tried script like this but, it does work well when page takes a bit longer to load than specified in Ajax Script

HTML:

<div class="row row_sep">
<div class="col-lg-12">

<div class="col-lg-2">
   <select name="prov" id="prov" class="form-control input-sm b_border">
    <option value="0">Provincia</option>
    {% for provincia in provincias %}
    <option value="{{ provincia.id }}" {% if get.prov == provincia.id %} selected  {% endif %} > {{ provincia.name }} </option>
    {% endfor %}
   </select>
</div>

<div class="col-lg-2">
 <select name="zona" id="zona" class="form-control input-sm b_border">
   <option value="0">Zona</option>
 </select>
</div>

<div class="col-lg-2">
 <select name="city" id="city" class="form-control input-sm b_border">
   <option value="0">Municipio</option>
 </select>
</div>

<div class="col-lg-2">
 <select name="barrio" id="barrio" class="form-control input-sm b_border">
  <option value="0">Barrio</option>
 </select>
</div>

</div>
</div>

JS/AJAX:

<script>
$( document ).ready(function() { if ($('#prov').val() != "0") $('#prov').change() });
$('#prov').on('change', function() {
    var self = $(this);

    $.ajax({
        url: "{{ baseUrl }}/ajax-prov",
        type: 'GET',
        data: { id: self.val() },
        dataType: 'json',
        success: function(response){
            console.log(response);
            var $zona = $("#zona");
            $zona.empty(); // remove old options

            var $city = $("#city");
            $city.empty(); // remove old options

            var $barrio = $("#barrio");
            $barrio.empty(); // remove old options

            $("#zona").append('<option value="">Seleciona la Zona</option>');
            $.each(response.prov, function(i, state) {
                {% if get.zona is defined and get.zona != empty %}
                    if({{get.zona}} == state.id){
                        $("#zona").append('<option value="'+ state.id +'" selected>' + state.name + '</option>');
                    }else{
                        $("#zona").append('<option value="'+ state.id +'">' + state.name + '</option>');
                    }
                {% else %}
                    $("#zona").append('<option value="'+ state.id +'">' + state.name + '</option>');
                {% endif %}

             });

            //$("#zona").append('<option value="">' + response.res[0].name + '</div>');
        } 
    });
});

$( document ).ready(function() {
    setTimeout(function() {
        if ($('#zona').val() != "0") $('#zona').change() 
    }, 100);
});

$('#zona').on('change', function() {
    var self = $(this);

    $.ajax({
        url: "{{ baseUrl }}/ajax-zone",
        type: 'GET',
        data: { id: self.val() },
        dataType: 'json',
        success: function(response){

            var $city = $("#city");
            $city.empty(); // remove old options

            var $barrio = $("#barrio");
            $barrio.empty(); // remove old options

            $("#city").append('<option value="">Seleciona la Municipio</option>');
            $.each(response.zone, function(i, state) {
                {% if get.city is defined and get.city != empty %}
                    if({{get.city}} == state.id){
                        $("#city").append('<option value="'+ state.id +'" selected>' + state.name + '</option>');
                    }else{
                        $("#city").append('<option value="'+ state.id +'">' + state.name + '</option>');
                    }
                {% else %}
                    $("#city").append('<option value="'+ state.id +'">' + state.name + '</option>');
                {% endif %}

            });

            //$("#zona").append('<option value="">' + response.res[0].name + '</div>');
        }

    });
});

$( document ).ready(function() {
    setTimeout(function() {
        if ($('#city').val() != "0") $('#city').change() 
    }, 350);
});

$('#city').on('change', function() {
    var self = $(this);

    $.ajax({
        url: "{{ baseUrl }}/ajax-municipio",
        type: 'GET',
        data: { id: self.val() },
        dataType: 'json',
        success: function(response){

            var $city = $("#barrio");
            $city.empty(); // remove old options

            $("#barrio").append('<option value="">Seleciona el barrio</option>');
            $.each(response.barrio, function(i, state) {
                {% if get.barrio is defined and get.barrio != empty %}
                    if({{get.barrio}} == state.id){
                        $("#barrio").append('<option value="'+ state.id +'" selected>' + state.name + '</option>');
                    }else{
                        $("#barrio").append('<option value="'+ state.id +'">' + state.name + '</option>');
                    }
                {% else %}
                    $("#barrio").append('<option value="'+ state.id +'">' + state.name + '</option>');
                {% endif %}

            });

            //$("#zona").append('<option value="">' + response.res[0].name + '</div>');
        }

    });
});

$('#city').on('click', function() {
    var self = $(this);

    $.ajax({
        url: "{{ baseUrl }}/ajax-municipio",
        type: 'GET',
        data: { id: self.val() },
        dataType: 'json',
        success: function(response){

            var $city = $("#barrio");
            $city.empty(); // remove old options

            $("#barrio").append('<option value="">Seleciona el barrio</option>');
            $.each(response.barrio, function(i, state) {
                {% if get.barrio is defined and get.barrio != empty %}
                    if({{get.barrio}} == state.id){
                        $("#barrio").append('<option value="'+ state.id +'" selected>' + state.name + '</option>');
                    }else{
                        $("#barrio").append('<option value="'+ state.id +'">' + state.name + '</option>');
                    }
                {% else %}
                    $("#barrio").append('<option value="'+ state.id +'">' + state.name + '</option>');
                {% endif %}

            });

            //$("#zona").append('<option value="">' + response.res[0].name + '</div>');
        }

    });
});
</script>

I can't find good solution to make it work. You can preview the script on website http://mediainmuebles.es to get good idea.

Any suggestion how to make it work are highly appreciated. Thanks in advance.

Upvotes: 0

Views: 91

Answers (1)

Igor Adamenko
Igor Adamenko

Reputation: 878

For example you may check value of dropdown after your $.each call (because iterates over the array synchronously) instead of using setTimeout:

I think, something like this:

$.each(response.prov, function(i, state) {
    {% if get.zona is defined and get.zona != empty %}
        if ({{ get.zona }} == state.id){
            $("#zona").append('<option value="'+ state.id +'" selected>' + state.name + '</option>');
        } else {
            $("#zona").append('<option value="'+ state.id +'">' + state.name + '</option>');
        }
    {% else %}
        $("#zona").append('<option value="'+ state.id +'">' + state.name + '</option>');
    {% endif %}
});

{% if get.zona is defined and get.zona != empty %}
    $('#zona').change();
{% endif %}

Upvotes: 1

Related Questions