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
Here is what the currencies
Object looks like:
There’s many more supported currencies but this is enough for this tutorial.
Next let’ populate the
<select> elements using
The HTML is generated with the
getOptions function that looks like this:
This loops through the
currencies Object and generates the
Next we’ll add an
eventListener to detect when the button is clicked:
This calls a
fetchCurrencies function on click that looks like this:
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:
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.