Bộ lọc select tỉnh thành, quận huyện sử dựng API provinces.open-api.vn

banner home FINAL 1050x121 1
huong dan su dung wordpress 2

Bộ lọc select tỉnh thành, quận huyện sử dựng API provinces.open-api.vn

Đây là bộ lọc quận huyện sử dụng API từ provinces.open-api.vn (API này được cập nhật liên tục nên không lo lỗi vị trí nhé)

<div>
<select id="city">
<option value="" selected>Chọn tỉnh thành</option>           
</select>
<select id="district">
<option value="" selected>Chọn quận huyện</option>
</select>
<select id="ward">
<option value="" selected>Chọn phường xã</option>
</select>
</div> 
<h2 id="result"></h2>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" referrerpolicy="no-referrer"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
    <script>
    const host = "https://provinces.open-api.vn/api/";
var callAPI = (api) => {
    return axios.get(api)
        .then((response) => {
            renderData(response.data, "city");
        });
}
callAPI('https://provinces.open-api.vn/api/?depth=1');
var callApiDistrict = (api) => {
    return axios.get(api)
        .then((response) => {
            renderData(response.data.districts, "district");
        });
}
var callApiWard = (api) => {
    return axios.get(api)
        .then((response) => {
            renderData(response.data.wards, "ward");
        });
}
var renderData = (array, select) => {
    let row = ' <option disable value="">Chọn</option>';
    array.forEach(element => {
        row += `<option data-id="${element.code}" value="${element.name}">${element.name}</option>`
    });
    document.querySelector("#" + select).innerHTML = row
}
$("#city").change(() => {
    callApiDistrict(host + "p/" + $("#city").find(':selected').data('id') + "?depth=2");
    printResult();
});
$("#district").change(() => {
    callApiWard(host + "d/" + $("#district").find(':selected').data('id') + "?depth=2");
    printResult();
});
$("#ward").change(() => {
    printResult();
})
var printResult = () => {

    if ($("#district").find(':selected').data('id') != "" && $("#city").find(':selected').data('id') != "" &&

        $("#ward").find(':selected').data('id') != "") {

        let result = $("#city option:selected").text() +

            " | " + $("#district option:selected").text() + " | " +

            $("#ward option:selected").text();

        $("#result").text(result)

    }
}

</script>

Liên hệ Zalo/Viber để được hỗ trợ: 0918 99 2587
0/5 (0 Reviews)

# KHÁM PHÁ CÁC HASHTAG HÀNG ĐẦU

Theo dõi và cập nhật tin tức AZ9s thông qua các kênh truyền thông:

- Zalo Channel

- Facebook Channel

- Youtube Channel

banner home FINAL 1050x121 1
0 0 votes
Article Rating
Nhận thông báo qua Email
Nhận thông báo cho
guest

0 Comments
Inline Feedbacks
View all comments
0
Hãy để lại bình luận của bạn!x
()
x