CurrencyConverter5 / script.js
GarGerry's picture
Create script.js
52bf539 verified
raw
history blame
1.04 kB
async function convertCurrency() {
const amount = document.getElementById('amount').value;
const fromCurrency = document.getElementById('fromCurrency').value;
const toCurrency = document.getElementById('toCurrency').value;
const resultDiv = document.getElementById('result');
if (!amount || amount <= 0) {
resultDiv.innerHTML = "Please enter a valid amount!";
return;
}
try {
const apiKey = 'YOUR_API_KEY'; // Replace with your API key
const url = `https://v6.exchangeratesapi.io/latest?base=${fromCurrency}&symbols=${toCurrency}&access_key=${apiKey}`;
const response = await fetch(url);
const data = await response.json();
if (data.error) {
resultDiv.innerHTML = "Error fetching data.";
} else {
const rate = data.rates[toCurrency];
const convertedAmount = (amount * rate).toFixed(2);
resultDiv.innerHTML = `${amount} ${fromCurrency} = ${convertedAmount} ${toCurrency}`;
}
} catch (error) {
resultDiv.innerHTML = "Error fetching conversion rate.";
}
}