-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcountryStateCity.html
114 lines (103 loc) · 3.19 KB
/
countryStateCity.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Country State City</title>
<link rel="stylesheet" href="countryStateCity.css" />
</head>
<body>
<div id="wrapper">
<h1>Fetching State & City by Country</h1>
<div class="container">
<select name="" id="country">
<option value="" selected disabled>Select Country</option>
</select>
<select name="" id="state">
<option value="" selected disabled>Select State</option>
</select>
<select name="" id="city">
<option value="" selected disabled>Select City</option>
</select>
</div>
</div>
<script>
const country = document.querySelector("#country");
const state = document.querySelector("#state");
const city = document.querySelector("#city");
const API_KEY =
"TjZNU1M4VDR1UUlVeVNDdFlXMVdBWFIzUGs0Q016eXhPY0F0cUZydA==";
const headers = new Headers();
headers.append("X-CSCAPI-KEY", API_KEY);
const requestOptions = {
method: "GET",
headers: headers,
redirect: "follow",
};
function fetchData() {
fetch("https://api.countrystatecity.in/v1/countries", requestOptions)
.then((response) => response.text())
.then((result) => {
showCountries(result);
})
.catch((error) => console.log("error", error));
}
fetchData();
function showCountries(data) {
data = JSON.parse(data);
for (let i = 0; i < data.length; i++) {
const opt = document.createElement("option");
opt.innerHTML = data[i].name;
opt.value = data[i].iso2;
country.append(opt);
}
}
country.onchange = () => {
getState(country.value);
};
function getState(element) {
fetch(
"https://api.countrystatecity.in/v1/countries/" + element + "/states",
requestOptions
)
.then((response) => response.text())
.then((result) => {
showStates(result);
})
.catch((error) => console.log("error", error));
}
function showStates(data) {
data = JSON.parse(data);
state.innerHTML =
"<option value='' selected disabled>Select State</option>";
for (let i = 0; i < data.length; i++) {
const opt = document.createElement("option");
opt.innerHTML = data[i].name;
opt.value = data[i].iso2;
state.append(opt);
}
}
state.onchange = () => {
getCity(state.value);
};
function getCity(element) {
fetch(
"https://api.countrystatecity.in/v1/countries/" +
country.value +
"/states/" +
element +
"/cities",
requestOptions
)
.then((response) => response.text())
.then((result) => {
showCities(result);
})
.catch((error) => console.log("error", error));
}
function showCities(data) {
console.log(data);
}
</script>
</body>
</html>