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

https://github.com/stommazh/vietnamlocalselector

Hoặc

Hoac

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:

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

Đã 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

<!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é .

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

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ả 🤩🤩🤩🤩

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é ^^.

Last updated

Navigation

Lionel

@Copyright 2023