Currency converter with HTML & JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<title>Currency converter with HTML & JavaScript</title> | |
<link rel="stylesheet" href="style.css" /> | |
</head> | |
<body> | |
<form> | |
<input id="amount" type="number" value="1" /> | |
<select id="primary" class="input"></select> | |
<select id="secondary" class="input"></select> | |
<input id="btn-convert" type="button" value="Convert" /> | |
</form> | |
<p id="result" style="display:none;"> | |
<span id="txt-primary"></span> | |
<span id="txt-secondary"></span> | |
</p> | |
<script> | |
const currencies = { | |
AUD: "Australian Dollar", | |
CAD: "Canadian Dollar", | |
EUR: "Euro", | |
GBP: "British Pound", | |
INR: "Indian Rupee", | |
JPN: "Japanese Yen", | |
USD: "United States Dollar", | |
ZAR: "South African Rand", | |
}; | |
const primaryCurrency = document.getElementById("primary"); | |
const secondaryCurrency = document.getElementById("secondary"); | |
primaryCurrency.innerHTML = getOptions(currencies); | |
secondaryCurrency.innerHTML = getOptions(currencies); | |
function getOptions(data) { | |
return Object.entries(data) | |
.map(([country, currency]) => `<option value="${country}">${country} | ${currency}</option>`) | |
.join(""); | |
} | |
document.getElementById("btn-convert").addEventListener("click", fetchCurrencies); | |
function fetchCurrencies() { | |
const primary = primaryCurrency.value; | |
const secondary = secondaryCurrency.value; | |
const amount = document.getElementById("amount").value; | |
fetch("https://v6.exchangerate-api.com/v6/d14eeee6a4f935aab34c335e/latest/" + primary) | |
.then((response) => { | |
if (response.ok) { | |
return response.json(); | |
} else { | |
throw new Error("NETWORK RESPONSE ERROR"); | |
} | |
}) | |
.then((data) => { | |
console.log(data); | |
displayCurrency(data, primary, secondary, amount); | |
}) | |
.catch((error) => console.error("FETCH ERROR:", error)); | |
} | |
function displayCurrency(data, primary, secondary, amount) { | |
const calculated = amount * data.conversion_rates[secondary]; | |
document.getElementById("result").setAttribute("style", "display:block"); | |
document.getElementById("txt-primary").innerText = amount + " " + primary + " = "; | |
document.getElementById("txt-secondary").innerText = calculated + " " + secondary; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source => https://w3collective.com/currency-converter-html-javascript/