-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
51 lines (45 loc) · 1.64 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
let api = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/USD`;
const fromDropDown = document.getElementById("from-currency-select");
const toDropDown = document.getElementById("to-currency-select");
//Creacion de desplegable a partir de la matriz de divisas
currencies.forEach((currency) => {
const option = document.createElement("option");
option.value = currency;
option.text = currency;
fromDropDown.add(option);
});
//Repeticion para el otro desplegable
currencies.forEach((currency) => {
const option = document.createElement("option");
option.value = currency;
option.text = currency;
toDropDown.add(option);
});
//Establecimiento de valores automaticos
fromDropDown.value = "MXN";
toDropDown.value = "USD";
let convertCurrency = () => {
//Crear referencias
const amount = document.querySelector("#amount").value;
const fromCurrency = fromDropDown.value;
const toCurrency = toDropDown.value;
//Si el campo de entrada del importe no esta vacio
if (amount.length != 0) {
fetch(api)
.then((resp) => resp.json())
.then((data) => {
let fromExchangeRate = data.conversion_rates[fromCurrency];
let toExchangeRate = data.conversion_rates[toCurrency];
const convertedAmount = (amount / fromExchangeRate) * toExchangeRate;
result.innerHTML = `${amount} ${fromCurrency} = ${convertedAmount.toFixed(
2
)} ${toCurrency}`;
});
} else {
alert("Please fill in the amount");
}
};
document
.querySelector("#convert-button")
.addEventListener("click", convertCurrency);
window.addEventListener("load", convertCurrency);