-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (62 loc) · 2.21 KB
/
index.js
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
/*Get the from and to select elements */
const fromSelect = document.querySelector('#from');
const toSelect = document.querySelector('#to');
/*Make an API call to get the list of currencies */
fetch('https://api.exchangerate.host/symbols')
.then((response) => {
/*Convert the response to JSON */
return response.json();
})
.then((data) => {
/*Get the list of currency codes */
const currencies = data.symbols;
/* Create an option element for each currency code*/
for (const code in currencies) {
const option = document.createElement('option');
/* console.log(code)*/
option.value = code;
option.textContent = code;
/* Add the option element to the from and to select elements*/
fromSelect.appendChild(option.cloneNode(true));
toSelect.appendChild(option.cloneNode(true));
}
})
.catch((error) => {
/* Handle any errors that may occur*/
console.error(error);
});
/* Get the form element*/
const form = document.querySelector('form');
/* Add an event listener for the submit event*/
form.addEventListener('submit', (event) => {
/* Prevent the default action of the form submission*/
event.preventDefault();
/* Perform the currency conversion and update the page*/
convertCurrency();
});
function convertCurrency() {
/* Get the amount, from, and to values from the form*/
const amount = document.querySelector('#amount').value;
const from = document.querySelector('#from').value;
const to = document.querySelector('#to').value;
/* Make an API call to convert the currency*/
fetch(`https://api.exchangerate.host/convert?from=${from}&to=${to}&amount=${amount}`)
.then((response) => {
/* Convert the response to JSON*/
return response.json();
}).then((data) => {
/* Check if the conversion was successful*/
if (data.success) {
/* Update the converted amount */
const converted_Amount = data.result;
document.querySelector('#converted_Amount').textContent = converted_Amount;
} else {
/* Display an error message */
alert(data.error);
}
})
.catch((error) => {
/* Handle any errors that may occur */
console.error(error);
});
}