Home > other >  Can't add selector with options to DOM with fetching api
Can't add selector with options to DOM with fetching api

Time:10-18

this is my first question here, so I'm little bit nervous ;) My problem is, how to add selector with options to DOM. Main question is that I have api to get data and the value of options should be added from this api. At the beginning I create button to start the function, but then code doesn't work. Here is my code:

const btn = document.createElement("button");
btn.setAttribute("id", "getCurrencies");
btn.innerHTML = "Click me!";
document.body.appendChild(btn);

btn.addEventListener("click", (e) => {
  fetch("https://api.frankfurter.app/latest")
    .then((response) => response.json)
    .then((data) => {
      const selectEL = createElement("select");
      const currencies = Object.entries(data.rates).forEach(([code, value]) => {
        const optionEl = createElement("option");
        // optionEl.setAttribute("value", code);
        optionEl.innerHTML = ($[code], $[value]);
        selectEL.appendChild(optionEl);
      });
      document.body.appendChild(selectEL);
    })
    .catch((err) => console.log(err));
});

CodePudding user response:

You have multiple mistakes. Start debugging your code piece by piece. If you first look at the console you will get error "ReferenceError: createElement is not defined"

  1. createElement calls for select and option are not going to work, you are missing WHERE in the document to create them. document.createElement works like in the first line of code.

Then you fix those and get the next error "TypeError: Cannot convert undefined or null to object"

  1. You are not calling response.json(). It doesn't do the conversion without calling the function. So it will give typeError.

Then you fix the json call. You will now get error "ReferenceError: $ is not defined" This means $ is not defined and the transpiler has no idea what to do. By looking at your code:

  1. Your innerHTML set is wrong. You could use es6 string optionEl.innerHTML = ${code} - ${value};

Now it starts to work.

  1. I would split the code to functions so it is easier to read.

So start by debugging from the beginning. Remove code lines and read what the console prints for you.

See working example without code splitting: https://codepen.io/shnigi/pen/NWvNwXQ

CodePudding user response:

You should do it like this:

$(document).on('click','#getCurrencies',function(){
 // ...
});

This binds a click event to the document and all child elements within it. This method is referred to as delegated event handling.

  • Related