Primary JS realizes the three-level linkage selection of provinces, cities and counties

Posted by mukeshgulia on Mon, 24 Jun 2019 00:27:46 +0200

Original address Look at it.

Write in front

Some time ago, I wrote something about the weather. The choice of cities in the provinces and cities (counties) made me very headache. Most of the searches on the Internet relied on plug-ins or third-party libraries. I felt that the code would be very heavy, so I simply realized several ways of city selection once in a while in order to meet the needs of the future. These three methods are all for the pc side, and are implemented using native js, even jq is not used, so the code is a bit cumbersome (embarrassing)... But let me finish the principle.

Source code address Portal

Preview Address Portal

Method 1: Pull-down Selection Box to realize three-level linkage of provinces, cities and counties

  1. It is very common and convenient to use drop-down frame to realize three-level linkage between provinces and urban areas. Here you need to first understand the related attributes of select and its object attributes, please refer to This article
  2. First, look at the final results:
  3. Introduction of ideas:
    • When the page is loaded, the list of provinces is dynamically obtained and placed in the drop-down item of the drop-down menu:
    /*Auto-loading provincial list*/
(function showProv() {
    btn.disabled = true;
    var len = provice.length;
    for (var i = 0; i < len; i++) {
        var provOpt = document.createElement('option');
        provOpt.innerText = provice[i]['name'];
        provOpt.value = i;
        prov.appendChild(provOpt);
    }
})();
  • When you click on an item in the provinces list, the onchange event in the provinces drop-down box is triggered. In the onchange event, the corresponding cities are displayed according to the preferred provinces. Here we use a selected selected index attribute to get which province we just clicked on (value attribute value was added to generate the list of provinces):
    var val = obj.options[obj.selectedIndex].value;  
    //What we get here is the number of drop-down items for the selected provinces.
  • When clicking on an item in the city list, the principle is the same as above (not repeated here).
  • When choosing a city, there are two situations. If there are no counties and districts under the urban option, the selected provinces and cities will be displayed directly in the input box, otherwise the counties and districts will be displayed according to the principle of appeal.
    <!--The method is to judge the county area. length Is it0-->
    var countryLen = provice[current.prov]["city"][val].districtAndCounty.length;
        if(countryLen == 0){
            addrShow.value = provice[current.prov].name + '-' + provice[current.prov]["city"][current.city].name;
            return;
        }
  • Finally, click on the county area and then press OK to display the selected location in the input box.

    1. Be careful:
      • When a specific county is not selected, the button is in a non-point state.
      • Specific implementation is mainly based on urban data for more detailed processing.
    2. Explain:
      • The provincial and urban data used here are from the network, which can not guarantee the authenticity and integrity, but only for the use of cases.
      • The data type used here is a js array. The format is as follows( Full Edition):
var provice = [
    {
        name: "Beijing",
        city: [
            {
                name: "Beijing",
                districtAndCounty: ["Dongcheng District", "Xicheng District", "Chongwen District", "Xuanwu District", "Chaoyang District", "Fengtai District", "Shijingshan District", "Haidian District", "Mentougou area", "Fangshan District", "Tongzhou District", "Shunyi District", "Changping District", "Daxing District", "Huairou District", "Pinggu District", "Miyun County", "Yanqing County", "Yanqing Town"]
            }
        ]
    },

    ......

    {
        name: "Hebei Province",
        city: [
            {
                name: "Shijiazhuang City",
                districtAndCounty: ["Chang'an District", "Qiaodong District", "Qiaoxi District", "Xinhua District", "Yuhua District", "Jingxing Mining District", "Xinji", "Gaocheng", "Jinzhou City", "Xinle City", "Luquan", "Jingxing County", "Weishui Town", "Zhengding County", "Zhengding Town", "Luancheng County", "Luancheng Town", "Xingtang County", "Longzhou Town", "Lingshou County", "Lingshou Town", "Gaoyi County", "Gaoyi Town", "Shenze County", "Shenze Town", "Zanhuang County", "Zanhuang Town", "Wuji County", "Wuji Town", "Pingshan County", "shan zhen", "Yuanshi County", "Huaiyang Town", "Zhaoxian County", "Zhaozhou Town"]
            },

            .......

            {
                name: "Handan City",
                districtAndCounty: ["Congtai District", "Hanshan District", "Renaissance Area", "Fengfeng Mining Area", "Wu'an City", "Handan County",.....,"Quzhou County", "Quzhou Town"]
            }
        ]
    }
]

Method 2: Select provinces, counties and districts by level

  1. This is a better way to look and operate than the drop-down box above, but the logic is a bit similar. The provincial and urban data used are consistent with those above.
  2. First look at the effect of this method:
  3. The list of all provinces is also displayed first when the page is loaded (in a similar way)
  4. When clicking on a specific province, the list of provinces is replaced by a corresponding list of cities. When clicking on a specific city, the corresponding counties and districts are displayed. The implementation is as follows:
addrWrap.onclick = function (e) {     //Delegate click events to the parent element of the list
    var n;
    var e = e || window.event;
    var target = e.target || e.srcElement;
    if (target && target.nodeName == 'LI') {
        /*Judge first that the current display area shows the part of the province or city.*/
        for (var z = 0; z < 3; z++) {
            if (titleWrap[z].className == 'titleSel')
                n = z;
        }
        /*Displayed Processing Functions*/
        switch (n) {
            case 0:
                showCity2(target.index);   //Click on an item in the list of provinces, and then display the list of cities.
                break;
            case 1:
                showCountry2(target.index);  //Click on an item in the city list, and then display the county list.
                break;
            case 2:
                selectCountry(target.index);  //Click on a specific county, then select the county.
                break;
            default:
                showProv2();
        }
    }
};



5. In each step clicked above, the index and value of the selected item are saved in an object so that the selected provinces and municipalities can be displayed in the input box by clicking the confirmation button.
6. When there is no County in the selected city, the treatment is the same as the first one.
7. When clicking on classification, the corresponding content is displayed, and the value of the saved object is processed at the same time:

        //Delegate the event to the parent element and process it according to the classification of clicks (html sets the value of li)
        if (target.value == '0') {
            showProv2();  
        } else if (target.value == '1') {
            showCity2(current2.prov);
        } else {
            showCountry2(current2.city);
        }
  1. OK

Method 3: Select cities in alphabetical order

  1. Selecting cities in alphabetical order is simpler, rougher and simpler than the first two, with fewer codes.
  2. First look at the effect of this method:
  3. Hot cities are displayed first when the page is loaded
  4. Click on different alphabets to display the corresponding list of cities
switch (index) {
            case 0:    //0 is a hot item
                showHotCity();
                break;
            case 6:    //6 is the last column and the number of alphabet sets is 2
                showCitys(index, 2);
                break;
            default:   //For the rest of the indexes, the number of alphabet sets is 4
                showCitys(index, 4);
        }
function showCitys(index, m) {
    //Intercept part of the city data from the incoming parameters as the current list of cities to be displayed
    var currentAll = cityAll.slice(4 * index - 3, 4 * index + m - 3);  

    .....

    //Place dynamically generated list items in the display area
}
  1. When you click on a specific city, display it in the input box.
  2. This method of urban data is different from the first two. It comes from the internet. It can not guarantee the authenticity and integrity. It is only for case use. The data format is as follows.( Full Edition):
var cityAll = [
    {
        name: "hot",
        citys: ["Beijing", "Shanghai", "Guangzhou", "Shenzhen", "Hangzhou", "Nanjing", "Chengdu", "Chongqing", "Wuhan", "Changsha", "Kunming"]
    },
    {
        name: "A",
        citys: ["ABA", "Alashan", "Ali", "Ankang", "Anqing", "Anshan", "Anshun", "Anyang", "Macao"]
    },

    ......


    {
        name: "Z",
        citys: ["Zaduo County", "Zanhuang County", "Zaoqiang County", "Zaoyang City", "Zaozhuang",.......,Ziyang"]
}

7. Perfection~

Summary

  1. See the links above for the detailed code, with comments (firefox and chrome can be displayed properly)~
  2. These ways of realization are my own opinions. Welcome the advice of the elders. If there is a better way to tell me, I will improve and perfect them.~
  3. Can someone tell me how to make a gif map?

Topics: Attribute network REST Firefox