-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostcode.js
More file actions
51 lines (39 loc) · 1.75 KB
/
Copy pathpostcode.js
File metadata and controls
51 lines (39 loc) · 1.75 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
const form = document.getElementById('form')
const apiURL = 'https://api.postcodes.io/postcodes/'
// adding event listner in form
form.addEventListener('submit', (e) => {
e.preventDefault()
searchValue = search.value.trim()
clearSearchResults()
searchPostCode(searchValue)
})
async function searchPostCode(searchValue) {
const searchResult = await fetch(`${apiURL}${searchValue}/nearest`)
console.log(searchResult)
if (searchResult.status == 404) {
alert('404 Error: Cannot find postcode, please enter a valid postcode.')
}
const data = await searchResult.json()
showData(data)
location.hash = searchValue
history.replaceState(null, null, searchValue);
}
function showData(data) {
const results = data["result"];
for (let i = results.length - 1; i >= 0; i--) {
const postcode = `<p class="mt-5">Postcode: <mark>${data.result[i].postcode}</mark></p>`
const country = `<p class="mt-5">Country: <mark>${data.result[i].country}</mark></p>`
const region = `<p class="mt-5">Region: <mark>${data.result[i].region}</mark></p>`
document.querySelector('#resultPostcode').insertAdjacentHTML('afterbegin', postcode)
document.querySelector('#resultCountry').insertAdjacentHTML('afterbegin', country)
document.querySelector('#resultRegion').insertAdjacentHTML('afterbegin', region)
}
document.querySelector('#backButton').insertAdjacentHTML('afterbegin',
"<a href='/' class='w-100 btn btn-lg btn-primary mt-5' type='submit'>Back</a>")
}
function clearSearchResults() {
document.querySelector("#resultPostcode").innerHTML = '';
document.querySelector("#resultCountry").innerHTML = '';
document.querySelector("#resultRegion").innerHTML = '';
document.querySelector("#backButton").innerHTML = '';
}