-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
51 lines (45 loc) · 1.6 KB
/
script.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
let api = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/USD`;
const fromDropDown = document.getElementById("from-currency-select");
const toDropDown = document.getElementById("to-currency-select");
//Create dropdown from the currencies array
currencies.forEach((currency) => {
const option = document.createElement("option");
option.value = currency;
option.text = currency;
fromDropDown.add(option);
});
//Repeat same thing for the other dropdown
currencies.forEach((currency) => {
const option = document.createElement("option");
option.value = currency;
option.text = currency;
toDropDown.add(option);
});
//Setting default values
fromDropDown.value = "USD";
toDropDown.value = "INR";
let convertCurrency = () => {
//Create References
const amount = document.querySelector("#amount").value;
const fromCurrency = fromDropDown.value;
const toCurrency = toDropDown.value;
//If amount input field is not empty
if (amount.length != 0) {
fetch(api)
.then((resp) => resp.json())
.then((data) => {
let fromExchangeRate = data.conversion_rates[fromCurrency];
let toExchangeRate = data.conversion_rates[toCurrency];
const convertedAmount = (amount / fromExchangeRate) * toExchangeRate;
result.innerHTML = `${amount} ${fromCurrency} = ${convertedAmount.toFixed(
2
)} ${toCurrency}`;
});
} else {
alert("Please fill in the amount");
}
};
document
.querySelector("#convert-button")
.addEventListener("click", convertCurrency);
window.addEventListener("load", convertCurrency);