#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

Build a simple currency converter with HTML & JavaScript

Last modified February 18th 2023 | GitHub Source Code [GitHub] | #html #js

In this tutorial we’ll be building a simple currency converter with HTML and JavaScript. We’ll be using exchangerate-api.com to fetch the real time currency prices so before getting started head over there and create yourself a free account to get your API key.

Let’s get started by creating the required HTML markup. We’ll need a form so users can enter the amount and the currencies they would like to convert. There’s also a paragraph that will be used to output the result of the converted currency:

<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>Code language: HTML, XML (xml)

You may have noticed that the <select> element doesn’t contain any <options>. We’ll populate this dynamically from the JavaScript. This will ensure both lists remain the same if currencies are added or removed and is just easier to maintain in general.

Here is what the currencies Object looks like:

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",
};Code language: JavaScript (javascript)

There’s many more supported currencies but this is enough for this tutorial.

Next let’ populate the <select> elements using innerHTML:

const primaryCurrency = document.getElementById("primary");
const secondaryCurrency = document.getElementById("secondary");
primaryCurrency.innerHTML = getOptions(currencies);
secondaryCurrency.innerHTML = getOptions(currencies);Code language: JavaScript (javascript)

The HTML is generated with the getOptions function that looks like this:

function getOptions(data) {
  return Object.entries(data)
    .map(([country, currency]) => `<option value="${country}">${country} | ${currency}</option>`)
    .join("");
}Code language: JavaScript (javascript)

This loops through the currencies Object and generates the <option> elements:

Next we’ll add an eventListener to detect when the button is clicked:

document.getElementById("btn-convert").addEventListener("click", fetchCurrencies);Code language: JavaScript (javascript)

This calls a fetchCurrencies function on click that looks like this:

function fetchCurrencies() {
  const primary = primaryCurrency.value;
  const secondary = secondaryCurrency.value;
  const amount = document.getElementById("amount").value;
  // Important: Include your API key below
  fetch("https://v6.exchangerate-api.com/v6/xxxxxxxxxxxxxxxxxxxxxx/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));
}Code language: JavaScript (javascript)

Here we’ve used the fetch method to make the API request of the primary currency selected. If the request was successful we then pass the data to a displayCurrency function that looks like this:

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;
}Code language: JavaScript (javascript)

This function multiples the amount that was entered into the form by the converted secondary currency. We then reveal the hidden result <p> and populate it with the converted currency text.

That’s all for this tutorial. You should have a working currency calculator that can be used as is or modified to suit other currency conversions tasks within a website or application. Why you’re here be sure to check out some of the related tutorials below.

Related Posts

#AD Shop Web Developer T-Shirts