-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
72 lines (63 loc) · 2.16 KB
/
script.js
File metadata and controls
72 lines (63 loc) · 2.16 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//Cotação de moedas do dia.
const USD = 5.37;
const EUR = 6.27;
const GBP = 7.17;
const form = document.querySelector("form");
const amount = document.getElementById("amount");
const currency = document.getElementById("currency");
const footer = document.querySelector("main footer");
const descripton = document.getElementById("description");
const result = document.getElementById("result");
//Manipulando o input amount para receber somente números.
// /\D+/g procura caracteres string
//replace vai substituir hasCharactersRegex por nada ""
amount.addEventListener("input", () => {
const hasCharactersRegex = /\D+/g;
amount.value = amount.value.replace(hasCharactersRegex, "");
});
//Capura submit
form.onsubmit = (event) => {
event.preventDefault();
switch (currency.value) {
case "USD":
convertCurrency(amount.value, USD, "US$");
break;
case "EUR":
convertCurrency(amount.value, EUR, "€");
break;
case "GBP":
convertCurrency(amount.value, GBP, "£");
break;
}
};
//Função converter moeda (no description)
function convertCurrency(amount, price, symbol) {
try {
//Exibindo a cotação da moeda selecionada
descripton.textContent = `${symbol}1 = ${formatCurrencyBRL(price)}`;
//Calcula o total
let total = amount * price;
// Verifica se o resultado não é um número
if (isNaN(total)) {
return alert("Por favor, digite o valor corretamente para converter.");
}
//Formata o total para BRL substituindo R$ por vazio
total = formatCurrencyBRL(total).replace("R$", "");
//Exibe o resultado total
result.textContent = `${total} Reais`;
//Aplica a classe que exibe o footer (resultado)
footer.classList.add("show-result");
} catch (error) {
console.log(error);
footer.classList.remove("show-result");
alert("Não foi possível converter. Tente novamente mais tarde.");
}
}
//Formata a moeda em Real Brasileiro (no description)
function formatCurrencyBRL(value) {
//Converte para número para utilizar o toLocaleString para formatar no padrão BRL (R$ 00,00)
return Number(value).toLocaleString("pt-BR", {
style: "currency",
currency: "BRL",
});
}