JSFiddle - React, Tailwind, and code Playground
HTML
<div class="wrap">
<input class="amount js-calc" type="number" placeholder="amount...">
<select class="currency js-calc"></select>
</div>
<div class="wrap">
<input class="amount js-calc" type="number" placeholder="amount...">
<select class="currency js-calc"></select>
</div>
CSS
.wrap {
margin: 4px;
}
JavaScript
"use strict";
const api_key = '8c054e387fa9a278b92a5e65d6d1883d';
const base_url = 'http://data.fixer.io/api/latest?';
// Если есть параметры программы, которые могут меняться руками,
// пусть будут в самом видном месте.
let RATES; /* = {
"EUR": 1,
"USD": 0.9,
...
} */
// Глобальная переменная, куда fetch присваивает список валют.
// Ожидаемый объект в виде коммента - полезное напоминание.
/***/
const _o = {
// мини-библиотека :)
all: function(selector, root) {
return (root || document).querySelectorAll(selector);
}
};
/***/
fetch(`${base_url}access_key=${api_key}`)
.then(response => response.json())
.then(data => __init__(data))
.catch(err => {
console.log(err);
alert("Что-то пошло не так.");
});
/***/
function __init__(data) {
/* data = {
rates: {
"EUR": 1,
"USD": 0.9,
...
}
} */
RATES /* GLOBAL */ = data.rates;
// какая-то метка, чтобы подчеркнуть, что это именно global, а не забытый let / const
let currency = _o.all(".currency"), amount = _o.all(".amount");
init_html();
init_listeners();
/***/
function init_html() {
currency[0].innerHTML = currency[1].innerHTML = Object.keys(RATES).map(key => {
return `<option>${key.toUpperCase()}</option>`;
});
currency[0].value = "EUR";
currency[1].value = "USD";
}
function init_listeners() {
_o.all(".js-calc").forEach(e => e.addEventListener("input", calc_exchange));
let wrap = [..._o.all(".wrap")];
function calc_exchange() {
let this_index = wrap.indexOf(this.closest(".wrap"));
let from_currency = currency[this_index].value.trim().toUpperCase();
let amount_old = (+amount[this_index].value || 0);
/***/
let other_index = +!this_index;
let to_currency = currency[other_index].value.trim().toUpperCase();
let amount_new = amount_old * RATES[to_currency] / RATES[from_currency];
amount[other_index].value = amount_new.toFixed(3);
}
}
}