Spaces:
Running
Running
// Mengambil elemen-elemen dari DOM | |
const amountInput = document.getElementById("amount"); | |
const fromCurrency = document.getElementById("from"); | |
const toCurrency = document.getElementById("to"); | |
const convertButton = document.getElementById("convert-btn"); | |
const swapButton = document.getElementById("swap-btn"); | |
const result = document.getElementById("result"); | |
// Data kurs mata uang (contoh) | |
const exchangeRates = { | |
"USD": { "EUR": 0.85, "IDR": 14200, "GBP": 0.75, "MYR": 4.20 }, | |
"EUR": { "USD": 1.18, "IDR": 16750, "GBP": 0.88, "MYR": 4.94 }, | |
"IDR": { "USD": 0.000070, "EUR": 0.000060, "GBP": 0.000053, "MYR": 0.00025 }, | |
"GBP": { "USD": 1.33, "EUR": 1.14, "IDR": 18850, "MYR": 5.60 }, | |
"MYR": { "USD": 0.24, "EUR": 0.20, "IDR": 3700, "GBP": 0.18 } | |
}; | |
// Fungsi untuk menghitung konversi mata uang | |
function convertCurrency() { | |
const amount = parseFloat(amountInput.value); | |
const from = fromCurrency.value; | |
const to = toCurrency.value; | |
if (isNaN(amount) || amount <= 0) { | |
result.textContent = "Please enter a valid amount."; | |
return; | |
} | |
const rate = exchangeRates[from][to]; | |
if (rate) { | |
const convertedAmount = (amount * rate).toFixed(2); | |
result.textContent = `${amount} ${from} = ${convertedAmount} ${to}`; | |
} else { | |
result.textContent = "Conversion rate not available."; | |
} | |
} | |
// Fungsi untuk menukar mata uang | |
function swapCurrencies() { | |
const temp = fromCurrency.value; | |
fromCurrency.value = toCurrency.value; | |
toCurrency.value = temp; | |
convertCurrency(); // Setelah swap, langsung hitung konversinya | |
} | |
// Event listener untuk tombol Convert | |
convertButton.addEventListener("click", convertCurrency); | |
// Event listener untuk tombol Swap | |
swapButton.addEventListener("click", swapCurrencies); | |
// Optionally, bisa tambahkan fitur untuk menghitung otomatis ketika ada perubahan input | |
amountInput.addEventListener("input", convertCurrency); | |
fromCurrency.addEventListener("change", convertCurrency); | |
toCurrency.addEventListener("change", convertCurrency); |