On document ready get cities by country id not working [ jquery custom plugin ]

470 views Asked by At

I made a jquery plugin to get cities on change of country drop down.

I want same functionality when updating the form on page load.

I don't want to repeat my code on document ready i want to reuse the code which i used in on change event.

For this is made a function and called it in document ready and on change event.

on calling function ajax is getting data but couldn't append it on city drop down

Here is my code before creating function for reuse in page load

This code is working but only for on change event of country drop down but now i want it to load cities from ajax on page load also

Only On change event of country drop down

$(document).ready(function () {

  (function ($) {
    //To Use getCities Function pass country drop down class selecter in parameter
    $.fn.getCities = function (countryClass) {
      $(document).on('change', countryClass, function () {
        var countryId = $(this).val();
        //Call Ajax to get cities by country id from ApplicationAjaxController's function getCitiesAction
        $.ajax({
          type: 'post',
          url: "{{ path('cms_application_city') }}",
          dataType: 'JSON',
          data: {
            countryId: countryId
          },
          success: function (res) {
            $('.CityName').css('display', 'none');
            if (res.success == 1) {
              var html = '';
              for (var key in res.cities) {
                var value = res.cities[key];
                html += '<option value="' + key + '">' + value + '</option>';
              }
              $("#ajax_citySelect").html(html);
              $("#ajax_citySelect").append('<option value="other">Other</option>');
              $("#ajax_citySelect").selectpicker('refresh');
              //Show and hide City Text field on changing city option
              $(document).on('change', '.citySelect', function () {
                if ($(this).val() == 'other') {
                  $('.CityName').css('display', 'block');
                } else {
                  $('.CityName').css('display', 'none');
                }
              });// end of city on change event
            } else {
              var html = '';
              html += '<option value="' + res.cities + '">' + res.cities + '</option>';
              $("#ajax_citySelect").html(html);
              $("#ajax_citySelect").append('<option value="other">Other</option>');
              $("#ajax_citySelect").selectpicker('refresh');
            }
          },
          error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus);
            if (jqXHR.status == 500) {
              alert('Internal error: ' + jqXHR.responseText);
            } else {
              alert('Unexpected error.');
            }
          }
        }); //end of ajax function
      });// end of country on change event
    };
  }(jQuery)); //end of plugin function

  $(".Country").getCities('.Country');
});

To add same functionality on pageload i made function and here is my code

but it's not working can anyone tell me what i am doing wrong ?

After add function to reuse on page load

 $(document).ready(function () {
        function AjaxCallBack(response){
            return response;
        }
        function getCityByCountry(countryClass) {
            var $cityField = $(countryClass).parent().parent().next().find('select.citySelect');
            var $cityTextFieldContainer = $cityField.parent().parent();
            $cityTextFieldContainer.next().find('.city').parent().parent().css('display', 'none');
            $cityTextFieldContainer.next().find('.city').parent().parent().css('display', 'none');
            var countryId = $(countryClass).val();
            $.ajax({
                'async': false,
                type: 'post',
                url: "{{ path('cms_application_city') }}",
                dataType: 'JSON',
                data: {
                    countryId: countryId
                },
                success: function (res) {
                    AjaxCallBack(res);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.');
                    }
                }
            });
        }

        (function ($) {
            $.fn.getCities = function (countryClass) {
                $(document).ready(function () {
                    var getRes = getCityByCountry(countryClass);

                    console.log(getCityByCountry(countryClass));

                   var html = '';
                    if (getRes.success == 1) {

                        var city_id = res.city_id;
                        var selected = '';
                        for (var key in res.cities) {
                            var value = res.cities[key];
                            selected = '';
                            if (city_id == key) {
                                selected = 'selected';
                            }
                            html += '<option value="' + key + '" ' + selected + '>' + value + '</option>';
                        }

                        if (city_id == 0) {
                            selected = 'selected';
                        }

                        html += '<option value="0" ' + selected + '>Other</option>';
                        $cityField.html(html);
                        $cityField.selectpicker('refresh');
                        //Show and hide City Text field on changing city option
                        $(document).on('change', '.citySelect', function () {
                            if ($(this).val() == '0' || $(this).val() == 0) {
                                $cityTextFieldContainer.next().find('.city').parent().parent().css('display', 'block');
                            } else {
                                $cityTextFieldContainer.next().find('.city').parent().parent().css('display', 'none');
                            }
                        });
                    } else {
                        html += '<option value="' + res.cities + '">' + res.cities + '</option>';
                        html += '<option value="0" ' + selected + '>Other</option>';
                        $cityField.html(html);
                        $cityField.selectpicker('refresh');
                    }
                });
                $(document).on('change', countryClass, function () {
                    getCityByCountry(countryClass);
                });
            };
        }(jQuery));
        $(".Country").getCities('.Country');
    });
2

There are 2 answers

2
Reinstate Monica Cellio On BEST ANSWER

If I've understood your issue correctly it's actually a very simple fix. Once the code to handle the select change has been called, simply trigger a change event. Use the first piece of code you posted as you know this already worked for changes after the document was loaded, and then add this extra line of code after you call .getCities()...

$(".Country").trigger("change");
0
Owais Aslam On

I did it by just trigger change event on document ready and it worked

$(".Country").trigger("change");