# Cách tích hợp bộ lọc select chọn nhanh Tỉnh, Thành & Quận, Huyện, districts, provinces (ok)

Api giao hàng nhanh: <https://viblo.asia/p/su-dung-api-giao-hang-nhanh-de-tinh-gia-cuoc-van-chuyen-1Je5EQB45nL>\
Token: 42d073a5-1f9c-11ed-8a70-52fa25d1292f

C:\xampp\htdocs\code\index.html

```
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
		<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script>
	</head>
	<body>
		<select name="calc_shipping_provinces" required="">
			<option value="">Tỉnh / Thành phố</option>
		</select>
		<select name="calc_shipping_district" required="">
			<option value="">Quận / Huyện</option>
		</select>
		<input class="billing_address_1" name="" type="hidden" value="">
		<input class="billing_address_2" name="" type="hidden" value="">
		<script type="text/javascript"src='districts.min.js'></script>
		<script type="text/javascript" src="script.js"></script>
	</body>
</html>
```

C:\xampp\htdocs\code

{% file src="/files/NsrbWyyN70RYDTAiaOmd" %}

{% file src="/files/UdguJ6I6mjo2qwbuhGSU" %}

{% file src="/files/UdguJ6I6mjo2qwbuhGSU" %}

![](/files/P8XicQjDEFtcEFTysn0h)

{% embed url="<https://github.com/hongquan/vn-open-api-provinces/>" %}

{% file src="/files/O5wSFlSo7N3oLPkbX214" %}

{% embed url="<https://github.com/hongquan/vn-provinces-vue-demo>" %}

{% file src="/files/s2SOpldO99HJJyzgMFrC" %}
<https://provinces.open-api.vn/api/?depth=3>
{% endfile %}

{% file src="/files/Hx6jwnj4MmyeByDVbJ78" %}

<https://github.com/stommazh/vietnamlocalselector>

Hoặc

{% file src="/files/NAGCTNLe24aK1q9xTiSy" %}

{% embed url="<https://github.com/kenzouno1/DiaGioiHanhChinhVN>" %}

Hoac

{% embed url="<https://github.com/ngoctan3006/vietnam-local-picker>" %}

{% file src="/files/TiJVA6IAuovINe4k91cL" %}

### DiaGioiHanhCHinhVN

Script tự động tải file excel từ website tổng cục thống kê <https://danhmuchanhchinh.gso.gov.vn/> và chuyển sang dạng cây json.

* Tỉnh
  * Id
  * Name
  * Districts
    * Id
    * Name
    * Wards
      * Id
      * Name
      * Level (Cấp hành chính phường,xã,thị trấn)

## Vietnam local selector - JavaScript plugin

*Create HTML Select element for Vietnam province, district and ward.*

### Basic usage

First, create 3 HTML Select elements for province, district and ward with name 'ls\_province', 'ls\_district' and 'ls\_ward' respectively:

```
<select name="ls_province"></select>
<select name="ls_district"></select>
<select name="ls_ward"></select>
```

Finally, include the plugin to your document,create instance of the plugin and pass the identify of selectors to an object as parameter:

```
<script src="vietnamlocalselector.js"></script>
<script>
	var localpicker = new LocalPicker({
		province: "ls_province",
		district: "ls_district",
		ward: "ls_ward"
    	});
</script>
```

### Options

```
  var options = {
  	    /*
            HTML Selector. You can pass value of name, id or class. 
            It will automatically detect exist elements for you.
            Example: 'myIdOrClass','#myId', '.myClass', 'myName'
            */
            province: 'ls_province',	
            district: 'ls_district',	
            ward: 'ls_ward',			
                      
            /*
            Define value for option tag. Valid option: id|name           
            */
            getValueBy: 'id',           
            
            //Placeholder text
            provinceText: 'Chọn tỉnh / thành phố',
            districtText: 'Chọn quận / huyện',
            districtNoText: 'Địa phương này không có quận / huyện',
            wardText: 'Chọn phường / xã',
            wardNoText: 'Địa phương này không có phường / xã',
            
            // Default value if no location exist
            emptyValue: " ",
            
            // Hide option where no local exist
            hideEmptyValueOption: true,
            
            // Hide place-holder option (first option)
            hidePlaceHolderOption: true,
            
            /*
            Include local level on option text as prefix
            Example: true = Quận Bình Thạnh | false = Bình Thạnh
            */
            provincePrefix: false,
            districtPrefix: true,
            wardPrefix: true,
            
            /*
            Include local level in option tag's attribute
            */
            levelAsAttribute: true,
            levelAttributeName: "data-level",
  };
```

[Xem bài viết:](https://nguyenthanhthinh.github.io/bo-loc-chon-tinh-thanh-quan-huyen-xa-phuong/?fbclid=IwAR0u-DWDY0U_ljkFnZq-LTSKkTMQWjcMon8bMEQa_A0vN07TdUXVxLY4ACo)

## Bộ lọc thay đổi Tỉnh Thành, Quận huyện, Xã phường

JavaScriptMay 23, 2021 · 11 mins read![Bộ lọc thay đổi Tỉnh Thành, Quận huyện, Xã phường](https://nguyenthanhthinh.github.io/assets/img/js/result.png)Share this[Share](https://www.addtoany.com/share#url=https%3A%2F%2Fnguyenthanhthinh.github.io%2Fbo-loc-chon-tinh-thanh-quan-huyen-xa-phuong%2F%3Ffbclid%3DIwAR0u-DWDY0U_ljkFnZq-LTSKkTMQWjcMon8bMEQa_A0vN07TdUXVxLY4ACo\&title=B%E1%BB%99%20l%E1%BB%8Dc%20thay%20%C4%91%E1%BB%95i%20T%E1%BB%89nh%20Th%C3%A0nh%2C%20Qu%E1%BA%ADn%20huy%E1%BB%87n%2C%20X%C3%A3%20ph%C6%B0%E1%BB%9Dng%20%7C%20Thinh%20Nguyen)[Facebook](https://nguyenthanhthinh.github.io/#facebook)[Twitter](https://nguyenthanhthinh.github.io/#twitter)

Đã lâu rồi mình không có làm website nói thật chứ mình thích web lắm mà không có cơ hội làm với nhiều lý do abcxyz :) . rãnh nên mình viết bài về web này nọ cho `có đam mê` lại với nghề ::)) Mình thấy bộ lọc này thường được sử dụng ở những website mình sẽ làm về nó từ giao diện đến cách xử lý nè :)) sử dụng `javascript` cơ bản và một số cú pháp `js mới` nhé ^^

Mình sử dụng `bootstrap 5` để làm giao diện . `cái nào mới là mình tò mò haha`

![js, javascript](https://nguyenthanhthinh.github.io/assets/img/js/ui-city.png)

```
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    <title>Bộ lọc thay đổi tỉnh thành quận huyện phường xã</title>
  </head>
  <body>
    <div class="container">
      <div class="row justify-content-md-center p-2">
        <div class="col-md-auto">
          <select class="form-select form-select-sm mb-3" id="city" aria-label=".form-select-sm">
            <option value="" selected>Chọn tỉnh thành</option>           
          </select>
          
          <select class="form-select form-select-sm mb-3" id="district" aria-label=".form-select-sm">
            <option value="" selected>Chọn quận huyện</option>
          </select>

          <select class="form-select form-select-sm" id="ward" aria-label=".form-select-sm">
            <option value="" selected>Chọn phường xã</option>
          </select>
        </div>    
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
  </body>
</html>
```

Giao diện mình đã làm xong, giờ thì mình sẽ đưa dữ liệu lên để hiển thị lên những `DropDownList` này. Thông thường thì sẽ là những api để đưa dữ liệu lên. Nhưng ở đây mình sẽ dùng `file json` mình kiếm được trên mạng [Truy cập vào để lấy file về nhé ](https://github.com/kenzouno1/DiaGioiHanhChinhVN/blob/master/data.json).

Mình sẽ dùng thư viện `Axios` để lấy dữ liệu `file json` nhé. mình sử dụng *CDN* của nó `<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>`.

Code thay đổi

```
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    <title>Bộ lọc thay đổi tỉnh thành quận huyện phường xã</title>
  </head>
  <body>
    <div class="container">
      <div class="row justify-content-md-center p-2">
        <div class="col-md-auto">
          <select class="form-select form-select-sm mb-3" id="city" aria-label=".form-select-sm">
            <option value="" selected>Chọn tỉnh thành</option>           
          </select>
          
          <select class="form-select form-select-sm mb-3" id="district" aria-label=".form-select-sm">
            <option value="" selected>Chọn quận huyện</option>
          </select>

          <select class="form-select form-select-sm" id="ward" aria-label=".form-select-sm">
            <option value="" selected>Chọn phường xã</option>
          </select>
        </div>    
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
    <script src="/app.js"></script>
  </body>
</html>
```

Tiếp ta tạo file `app.js` sau khi tạo xong file `app.js` ta thêm code như sau vào file `app.js`

```
var Parameter = {
    url: './data/vietnam.json',//Đường dẫn đến file chứa dữ liệu hoặc api do backend cung cấp
    method:'GET', //do backend cung cấp 
    responseType: 'application/json', //kiểu Dữ liệu trả về do backend cung cấp
}
//gọi ajax = axios => nó trả về cho chúng ta là một promise
var promise = axios(Parameter);
//Xử lý khi request thành công
promise.then(function(result) {
  console.log(result.data) 
});
```

kết quả như màn hình chúng ta đã thành công việc lấy dữ liệu về ::))) nói chứ làm ra là hứng thú nè haha, lập trình phải tò mò nhé mọi người không ra đừng nản nhé haha

![js, javascript](https://nguyenthanhthinh.github.io/assets/img/js/getdata.png)

Bây giờ là bước quan trọng nè ta sẽ đổ dữ liệu vào `DropDownList Tỉnh Thành`

Viết hàm `renderCity`

```
function renderCity(data){
    for (const x of data) {
        citis.options[citis.options.length] = new Option(x.Name, x.Id);
    }
}
```

Code cập nhật

```
var citis = document.getElementById("city"); 
var districts = document.getElementById("district");  
var wards = document.getElementById("ward"); 

var Parameter = {
    url: './data/vietnam.json',//Đường dẫn đến file chứa dữ liệu hoặc api do backend cung cấp
    method:'GET', //do backend cung cấp 
    responseType: 'application/json', //kiểu Dữ liệu trả về do backend cung cấp
}
//gọi ajax = axios => nó trả về cho chúng ta là một promise
var promise = axios(Parameter);
//Xử lý khi request thành công
promise.then(function(result) {
  renderCity(result.data);
});

function renderCity(data){
    for (const x of data) {
        citis.options[citis.options.length] = new Option(x.Name, x.Id);
    }
}
```

Khi mình thay đổi tỉnh thành nào thì sẽ hiển thị quận huyện ra. Trong javascript mình sẽ dùng event `onchange` nhé

```
function renderCity(data) {
  for (const x of data) {
    citis.options[citis.options.length] = new Option(x.Name, x.Id);
  }

  // xứ lý khi thay đổi tỉnh thành thì sẽ hiển thị ra quận huyện thuộc tỉnh thành đó
  citis.onchange = function () {
    district.length = 1;
    ward.length = 1;
    if(this.value != ""){
      const result = data.filter(n => n.Id === this.value);

      for (const k of result[0].Districts) {
        district.options[district.options.length] = new Option(k.Name, k.Id);
      }
    }
  };
 
}
```

Tương tự khi thay đổi quận huyện thì sẽ hiện thị phường xã

```
 // xứ lý khi thay đổi quận huyện thì sẽ hiển thị ra phường xã thuộc quận huyện đó
  district.onchange = function () {
    ward.length = 1;
    const dataCity = data.filter((n) => n.Id === citis.value);
    if (this.value != "") {
      const dataWards = dataCity[0].Districts.filter(n => n.Id === this.value)[0].Wards;

      for (const w of dataWards) {
        wards.options[wards.options.length] = new Option(w.Name, w.Id);
      }
    }
  };
```

Cập nhật toàn bộ code file `app.js`

```
var citis = document.getElementById("city");
var districts = document.getElementById("district");
var wards = document.getElementById("ward");
var Parameter = {
  url: "./data/vietnam.json", //Đường dẫn đến file chứa dữ liệu hoặc api do backend cung cấp
  method: "GET", //do backend cung cấp
  responseType: "application/json", //kiểu Dữ liệu trả về do backend cung cấp
};
//gọi ajax = axios => nó trả về cho chúng ta là một promise
var promise = axios(Parameter);
//Xử lý khi request thành công
promise.then(function (result) {
  renderCity(result.data);
});

function renderCity(data) {
  for (const x of data) {
    citis.options[citis.options.length] = new Option(x.Name, x.Id);
  }

  // xứ lý khi thay đổi tỉnh thành thì sẽ hiển thị ra quận huyện thuộc tỉnh thành đó
  citis.onchange = function () {
    district.length = 1;
    ward.length = 1;
    if(this.value != ""){
      const result = data.filter(n => n.Id === this.value);

      for (const k of result[0].Districts) {
        district.options[district.options.length] = new Option(k.Name, k.Id);
      }
    }
  };

   // xứ lý khi thay đổi quận huyện thì sẽ hiển thị ra phường xã thuộc quận huyện đó
  district.onchange = function () {
    ward.length = 1;
    const dataCity = data.filter((n) => n.Id === citis.value);
    if (this.value != "") {
      const dataWards = dataCity[0].Districts.filter(n => n.Id === this.value)[0].Wards;

      for (const w of dataWards) {
        wards.options[wards.options.length] = new Option(w.Name, w.Id);
      }
    }
  };
}
```

Thành quả 🤩🤩🤩🤩

![js, javascript](https://nguyenthanhthinh.github.io/assets/img/js/result.png)

*Do cấu trúc data mình vậy nên mình tùy biến lấy data . còn thực tế thì sẽ có những api cho riêng từng thằng tùy theo mỗi người viết hay ý đồ* nhưng logic cách xử lý thì tương tự. Lập trình thì mình tùy cơ ứng biến khi có thay đổi nhé ^^.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/advanced/cach-tich-hop-bo-loc-select-chon-nhanh-tinh-thanh-and-quan-huyen-districts-provinces-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
