-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
89 lines (63 loc) · 2.5 KB
/
script.js
File metadata and controls
89 lines (63 loc) · 2.5 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const currency_URL = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies";
const dropdowns = document.querySelectorAll(".dropdown select");
/*for(code in countryList){
console.log(code, countryList[code]);
}*/
// for country name
for(let select of dropdowns){
for(currCode in countryList){
let newOption = document.createElement("option");
newOption.innerText=currCode;
newOption.value=currCode;
/* fix USD for FROM and INR for TO at first take*/
if(select.name==="From" && currCode==="USD"){
newOption.selected="selected";
}
else if(select.name==="To" && currCode==="INR"){
newOption.selected="selected";
}
select.append(newOption);
// when new country get selected
select.addEventListener("change", (evt/*event object*/)=>{
updateFlag(evt.target);
});
}
}
// for country flag
const updateFlag = (element)=>{
//console.log(element);
let currCode = element.value;
//console.log(currCode);
let countryCode = countryList[currCode];
let newSrc = `https://flagsapi.com/${countryCode}/flat/64.png`;
// select ke parent pr jaenge => select-currency
let img = element.parentElement.querySelector("img");
img.src=newSrc;
}
// exchange rate
const btn = document.querySelector("form button");
const fromCurr = document.querySelector(".from select");
const toCurr = document.querySelector(".to select");
const result = document.querySelector(".result");
btn.addEventListener("click", async (evt)=>{
evt.preventDefault(); // no loading now
// access entered amount
let amount = document.querySelector(".amount input");
let amountVal=amount.value;
//console.log(amountVal);
if(amountVal==="" || amountVal<1){
amountVal=1;
amount.value="1";
}
//console.log(fromCurr.value , toCurr.value);
const URL = `${currency_URL}/${fromCurr.value.toLowerCase()}/${toCurr.value.toLowerCase()}.json`;
let response = await fetch(URL);
let data = await response.json();
let rate = data[toCurr.value.toLowerCase()];
//console.log(rate);
let finalAmount = amountVal * rate;
// result => 1 USD = 83 INR
result.innerText = `${amountVal} ${fromCurr.value} = ${finalAmount} ${toCurr.value}`;
result.style.fontSize="0.815rem";
result.style.fontFamily="Verdana, Geneva, Tahoma, sans-serif";
});