Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I display option inputs in HTML from API

I’m trying to fetch data from my API, and put it in ‘option’ input.
But all I’m geting is [object Object]. And I would like to get days of the week.

const daysOptions = document.querySelector("#days");

const getData = async (url) => {
  try {
    const res = await fetch(url);
    const data = await res.json();

    if (data.length > 0) {
      return data;
    }
  } catch (err) {
    alert(err);
  }
};

const createOptions = async () => {
  const dataDays = await getData("http://localhost:8080/v1/days/getdays");
  console.log(dataDays);

  dataDays.forEach((day) => {
    const selectOption = document.createElement("option");
    selectOption.value = day;
    // selectOption.id = id;
    selectOption.textContent = day;
    daysOptions.append(selectOption);
  });
};

createOptions();

What I’m fetching is:

0: {id: 1, day: 'Monday'}
1: {id: 2, day: 'Tuesday'}
2: {id: 3, day: 'Wednesday'}
3: {id: 4, day: 'Thursday'}
4: {id: 5, day: 'Friday'}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

After fetching when you are looping you should code like this below

dataDays.forEach((item) => {
  const selectOption = document.createElement("option");
  selectOption.value = item.day;
  // selectOption.id = id;
  selectOption.textContent = item.day;
  daysOptions.append(selectOption);
});

Here using the item I am accessing each object from the fetched list, and item.day is getting the value of the day.

if this solve your issue, let me know by replying or upvoting. Thanks

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading