-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
51 lines (39 loc) · 1.63 KB
/
Copy pathscript.js
File metadata and controls
51 lines (39 loc) · 1.63 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 converterForm = document.getElementById("converter-form");
const fromCurrency = document.getElementById("from-currency");
const toCurrency = document.getElementById("to-currency");
const amountInput = document.getElementById("amount");
const resultDiv = document.getElementById("result");
window.addEventListener("load", fetchCurrencies);
converterForm.addEventListener("submit", convertCurrency);
async function fetchCurrencies() {
// https://api.exchangerate-api.com/v4/latest/USD
const response = await fetch("https://api.exchangerate-api.com/v4/latest/USD");
const data = await response.json();
console.log(data);
const currencyOptions = Object.keys(data.rates);
currencyOptions.forEach((currency) => {
const option1 = document.createElement("option");
option1.value = currency;
option1.textContent = currency;
fromCurrency.appendChild(option1);
const option2 = document.createElement("option");
option2.value = currency;
option2.textContent = currency;
toCurrency.appendChild(option2);
});
}
async function convertCurrency(e) {
e.preventDefault();
const amount = parseFloat(amountInput.value);
const fromCurrencyValue = fromCurrency.value;
const toCurrencyValue = toCurrency.value;
if (amount < 0) {
alert("Please ener a valid amount");
return;
}
const response = await fetch(`https://api.exchangerate-api.com/v4/latest/${fromCurrencyValue}`);
const data = await response.json();
const rate = data.rates[toCurrencyValue];
const convertedAmount = (amount * rate).toFixed(2);
resultDiv.textContent = `${amount} ${fromCurrencyValue} = ${convertedAmount} ${toCurrencyValue}`;
}