| document.getElementById('currencyForm').addEventListener('submit', async function (event) { |
| event.preventDefault(); |
|
|
| |
| 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 = '3ebe2ccf9eeea2aaef280201'; |
| const url = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/${fromCurrency}`; |
|
|
| |
| const response = await fetch(url); |
| const data = await response.json(); |
|
|
| |
| if (data.result === 'error') { |
| resultDiv.innerHTML = `Error: ${data['error-type']}`; |
| } else { |
| |
| const rate = data.conversion_rates[toCurrency]; |
| const convertedAmount = (amount * rate).toFixed(2); |
| resultDiv.innerHTML = `${amount} ${fromCurrency} = ${convertedAmount} ${toCurrency}`; |
| } |
| } catch (error) { |
| resultDiv.innerHTML = "Error fetching conversion rate."; |
| console.error("Error:", error); |
| } |
| }); |
|
|
| |
| document.getElementById('swapButton').addEventListener('click', async function () { |
| const fromCurrency = document.getElementById('fromCurrency'); |
| const toCurrency = document.getElementById('toCurrency'); |
| const resultDiv = document.getElementById('result'); |
|
|
| |
| const tempCurrency = fromCurrency.value; |
| fromCurrency.value = toCurrency.value; |
| toCurrency.value = tempCurrency; |
|
|
| |
| const amount = document.getElementById('amount').value; |
|
|
| |
| if (amount && amount > 0) { |
| try { |
| const apiKey = '3ebe2ccf9eeea2aaef280201'; |
| const url = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/${fromCurrency.value}`; |
|
|
| |
| const response = await fetch(url); |
| const data = await response.json(); |
|
|
| if (data.result === 'error') { |
| resultDiv.innerHTML = `Error: ${data['error-type']}`; |
| } else { |
| const rate = data.conversion_rates[toCurrency.value]; |
| const convertedAmount = (amount * rate).toFixed(2); |
| resultDiv.innerHTML = `${amount} ${fromCurrency.value} = ${convertedAmount} ${toCurrency.value}`; |
| } |
| } catch (error) { |
| resultDiv.innerHTML = "Error fetching conversion rate."; |
| console.error("Error:", error); |
| } |
| } else { |
| |
| resultDiv.innerHTML = ""; |
| } |
| }); |
|
|