Looping through an array and injecting all the values into using jQuery?](https://stackoverflow.com/questions/740195/adding-options-to-a-select-using-jquery) – JkAlombro Jul 12 '22 at 09:51

  • @JkAlombro not really, I just try to do it it plain js and not use a library – Maolean Jul 12 '22 at 10:05
  • 1 Answers1

    0

    I'll just assume that the API is returning data, and I'll also assume the data structure of JSON object.

    Your fetch should look something like this:

    ...
    fetch(url)
        .then(res => res.json())
        .then(data => {
    
            if (!data) return; // Do something here
    
            // Get the select element
            var select = document.getElementById("dogTypes");
    
            // Iterate the data, create a <option> element and append it to
            // the select
            for (let i = 0; i < data.length; i++) {
                const element = data[i];
                
                var option = document.createElement("option");
                option.text = element.Name;
                option.value = element.Value;
    
                select.appendChild(option);
    
            }
    
        })
        .catch(err => {
            console.log(`error ${err}`)
        })
    
    Filipe Nóbrega
    • 564
    • 4
    • 18