-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
65 lines (58 loc) · 2.22 KB
/
main.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"use strict"
//Register SW later here
//first get a list of all currencies
fetch('https://free.currencyconverterapi.com/api/v6/currencies')
.then((response) => {
console.log(response)
return response.json();
})
.then(function (responseJson) {
let currencies = responseJson.results;
//loop through the currencies
for (const currency in currencies) {
const Symbol = currencies[currency].currencySymbol;
const Name = currencies[currency].currencyName;;
const Id = currencies[currency].id;
var node = document.createElement("option");
node.setAttribute('value', Id);
var textnode = document.createTextNode(`(${Id}) ${Name}`);
node.appendChild(textnode);
document.getElementById("from").appendChild(node);
}
for (const currency in currencies) {
const Symbol = currencies[currency].currencySymbol;
const Name = currencies[currency].currencyName;;
const Id = currencies[currency].id;
var node = document.createElement("option");
node.setAttribute('value', Id);
var textnode = document.createTextNode(`(${Id}) ${Name}`);
node.appendChild(textnode);
document.getElementById("to").appendChild(node);
}
})
.catch((err) => {
console.log(err);
})
//init variables
function convertCurrency(amount, from, to) {
from = document.querySelector('#from').value;
to = document.querySelector('#to').value;
amount = document.getElementById('value').value;
const query = `${from}_${to}`
const url = `https://free.currencyconverterapi.com/api/v6/convert?q=${query}&compact=ultra`
fetch(url).then(function (response) {
return response.json();
}).then(rates => {
let rate = rates[query];
const finalResult = rate * amount;
if (isNaN(finalResult)) {
alert('you need to fill all the fields')
} else {
document.getElementById('results').innerHTML = finalResult;
}
})
.catch(function (err) {
console.log(err)
})
}
//demo call the function