-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
49 lines (39 loc) · 1.72 KB
/
script.js
File metadata and controls
49 lines (39 loc) · 1.72 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
const amount = document.getElementById("amount")
const fromCurrency = document.getElementById("from_currency")
const toCurrency = document.getElementById("to_currency")
const convertedResult = document.getElementById("result")
const submitButton = document.getElementById("convert")
window.addEventListener("load",fetchcurrencies)
submitButton.addEventListener("click",(e)=>{e.preventDefault(); convertCurrency()})
async function fetchcurrencies() {
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)
console.log(currencyOptions)
currencyOptions.forEach(currency => {
const optionfrom = document.createElement("option")
optionfrom.value = currency;
optionfrom.textContent = currency;
fromCurrency.appendChild(optionfrom)
const optionto = document.createElement("option")
optionto.value = currency;
optionto.textContent = currency;
toCurrency.appendChild(optionto)
})
}
async function convertCurrency() {
const amountInput = parseFloat(amount.value)
const fromCurrencyValue = fromCurrency.value
const toCurrencyValue = toCurrency.value
if( amountInput < 0 ) {
alert("Please enter 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 = (amountInput*rate).toFixed(2)
const answer = `${amountInput} ${fromCurrencyValue} = ${convertedAmount} ${toCurrencyValue}`
convertedResult.textContent = answer;
}