-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountrySearch.js
More file actions
70 lines (54 loc) · 1.93 KB
/
countrySearch.js
File metadata and controls
70 lines (54 loc) · 1.93 KB
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
const input = document.getElementById('searchBox');
const select = document.getElementById('regionFilter');
const result = document.getElementById('main');
let allCountries = [];
function fetchAllCountries() {
fetch('https://restcountries.com/v3.1/all')
.then(res => res.json())
.then(data => {
allCountries = data;
displayCountries(allCountries);
})
.catch(err => {
result.innerHTML = `<p style="color:red;">데이터를 불러오지 못했습니다.</p>`;
});
}
function displayCountries(countries) {
const region = select.value.toLowerCase();
const filtered = countries.filter(country => {
if (region) {
return country.region.toLowerCase() === region;
}
return true;
});
if (filtered.length === 0) {
result.innerHTML = `<p style="color:red;">해당 조건에 맞는 국가가 없습니다.</p>`;
return;
}
result.innerHTML = filtered.map(country => `
<div class="country-card">
<h3>${country.name.common}</h3>
<img src="${country.flags.svg}" />
<p><strong>대륙:</strong> ${country.region}</p>
<p><strong>인구:</strong> ${country.population.toLocaleString()}명</p>
</div>
`).join('');
}
function searchCountries() {
const keyword = input.value.trim().toLowerCase();
const region = select.value.toLowerCase();
const matched = allCountries.filter(country => {
const nameMatches = country.name.common.toLowerCase().includes(keyword);
const regionMatches = region ? country.region.toLowerCase() === region : true;
return nameMatches && regionMatches;
});
displayCountries(matched);
}
let debounceTimer;
function debounceSearch() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(searchCountries, 500);
}
input.addEventListener('input', debounceSearch);
select.addEventListener('change', searchCountries);
fetchAllCountries();