main.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. fetch('https://open.er-api.com/v6/latest/USD').then(res => res.json())
  2. .then(data => {
  3. const currencyArray = Object.keys(data.rates)
  4. const currencyObj = data.rates;
  5. const updateDateTime = data.time_last_update_utc
  6. const selectCurrency = document.querySelectorAll('select.currency')
  7. const currencyOne = document.getElementById('currencyOne')
  8. const currencyTwo = document.getElementById('currencyTwo')
  9. const numberOne = document.getElementById('numberOne')
  10. const numberTwo = document.getElementById('numberTwo')
  11. const todayDate = document.getElementById('todayDate')
  12. todayDate.innerText = `${updateDateTime.slice(0, 16)}`
  13. for (let i = 0; i < selectCurrency.length; i++) {
  14. currencyArray.map(c => {
  15. let option = document.createElement("option")
  16. option.setAttribute('value', c)
  17. option.text = `${c}`
  18. selectCurrency[i].appendChild(option)
  19. })
  20. }
  21. const calcCurrency = () => {
  22. if (currencyOne.value === currencyTwo.value) {
  23. numberTwo.value = numberOne.value
  24. } else {
  25. let result = numberOne.value / currencyObj[currencyOne.value] * currencyObj[currencyTwo.value]
  26. numberTwo.value = result.toFixed(3)
  27. }
  28. }
  29. currencyOne.addEventListener("change", function () {
  30. calcCurrency()
  31. })
  32. currencyTwo.addEventListener("change", function () {
  33. calcCurrency()
  34. })
  35. numberOne.addEventListener("change", function () {
  36. calcCurrency()
  37. })
  38. })