app.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. let currencyRates = {}
  2. fetch('https://open.er-api.com/v6/latest/USD')
  3. .then(res => res.json())
  4. .then(data => {
  5. currencyRates = data.rates
  6. console.log(currencyRates)
  7. const ratesForm = document.forms.rates
  8. const firstField = ratesForm.first_field
  9. const secondField = ratesForm.second_field
  10. const firstList = ratesForm.first_list
  11. const secondList = ratesForm.second_list
  12. for (const key in currencyRates) {
  13. const newOption = new Option(key, currencyRates[key])
  14. firstList.append(newOption)
  15. secondList.append(newOption.cloneNode(true))
  16. }
  17. ratesForm.addEventListener("input", (event) => {
  18. const actionEl = event.target
  19. const firstCurrency = parseFloat(firstList.value)
  20. const secondCurrency = parseFloat(secondList.value)
  21. const firstAmount = parseFloat(firstField.value)
  22. const secondAmount = parseFloat(secondField.value)
  23. if (actionEl.closest(".input_container.col1") || actionEl.closest(".select_container.col2")) {
  24. if (firstAmount) {
  25. secondField.value = ((firstAmount * secondCurrency) / firstCurrency).toFixed(2)
  26. } else {
  27. secondField.value = 0
  28. }
  29. }
  30. if (actionEl.closest(".input_container.col2") || actionEl.closest(".select_container.col1")) {
  31. if (secondAmount) {
  32. firstField.value = ((secondAmount * firstCurrency) / secondCurrency).toFixed(2)
  33. } else {
  34. firstField.value = 0
  35. }
  36. }
  37. })
  38. })