-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
70 lines (61 loc) · 2.03 KB
/
script.js
File metadata and controls
70 lines (61 loc) · 2.03 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
//Cotação de moeda do dia
const USD = 4.87;
const EUR = 5.32;
const GBP = 6.08;
const amount = document.getElementById("amount");
const currency = document.getElementById("currency");
const form = document.querySelector("form");
const footer = document.querySelector("main footer");
const description = document.getElementById("description");
const result = document.getElementById("result");
//Manipulando o input amount para receber somente números
amount.addEventListener("input", () => {
const hasCharacterRegex = /\D+/g;
//Procura letras no input e substitui por ""(nada)
amount.value = amount.value.replace(hasCharacterRegex, "");
});
//Capiturando o envento de submit do formulário
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 para converter a moeda
function convertCurrency(amount, price, symbol) {
try {
// Exibindo a cotação da moeda selecionada
description.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");
}
// Formatar o valor total.
total = formatCurrencyBRL(total).replace("R$", "");
result.textContent = `${total} Reais`;
//Aplica a classe que exibe o footer para mostrar o resultado
footer.classList.add("show-result");
} catch (error) {
console.error(error);
//Remove a classe do footer removendo ele da tela
footer.classList.remove("show-result");
console.log(error);
alert("Não foi possível converter. Tente novamente mais tarde");
}
}
function formatCurrencyBRL(value) {
return Number(value).toLocaleString("pt-BR", {
style: "currency",
currency: "BRL",
});
}