Ujicobaconvert / script.js
GarGerry's picture
Update script.js
5c4f4ba verified
// Fungsi untuk melakukan konversi mata uang
async function convertCurrency() {
const amount = document.getElementById('amount').value;
const fromCurrency = document.getElementById('from-currency').value;
const toCurrency = document.getElementById('to-currency').value;
const result = document.getElementById('result');
const convertBtn = document.getElementById('convert-btn');
if (amount && fromCurrency && toCurrency) {
try {
// Menggunakan API dengan API key yang benar
const response = await fetch(`https://v6.exchangerate-api.com/v6/3ebe2ccf9eeea2aaef280201/latest/${fromCurrency}`);
const data = await response.json();
if (data.result === 'error') {
throw new Error('Error fetching exchange rates!');
}
const rate = data.rates[toCurrency];
const convertedAmount = (amount * rate).toFixed(2);
// Menampilkan hasil konversi
result.innerHTML = `${amount} ${fromCurrency} = ${convertedAmount} ${toCurrency}`;
// Menyembunyikan tombol Convert setelah konversi otomatis
convertBtn.style.display = 'none';
} catch (error) {
result.innerText = "Error fetching exchange rates!";
console.error('Error fetching exchange rates:', error);
}
}
}
// Fungsi untuk menukar mata uang From dan To
function swapCurrencies() {
const fromCurrency = document.getElementById('from-currency');
const toCurrency = document.getElementById('to-currency');
// Tukar nilai mata uang
const temp = fromCurrency.value;
fromCurrency.value = toCurrency.value;
toCurrency.value = temp;
// Lakukan konversi otomatis setelah swap
convertCurrency();
}
// Event listener untuk input amount agar otomatis konversi
document.getElementById('amount').addEventListener('input', convertCurrency);
// Event listener untuk perubahan mata uang (From dan To) agar tombol Convert muncul kembali
document.getElementById('from-currency').addEventListener('change', () => {
document.getElementById('convert-btn').style.display = 'block';
document.getElementById('result').innerHTML = '';
});
document.getElementById('to-currency').addEventListener('change', () => {
document.getElementById('convert-btn').style.display = 'block';
document.getElementById('result').innerHTML = '';
});