0

Am trying to populate static content on my web app from a database call which returns a JSON list of elements that I then would like to make the Option 1 populate with..

JSON returned:
{id: 0, categoryName: "General Discussion"},
.
.
.
{id: 7, categoryName: "Cleaning and Repairs"}

My call:

        $.get("http://localhost:8080/cc/sc/cat").done(function(categories) {
            var catList = document.getElementById("categories");
            var option = document.createElement("option");
            for (category in categories){
                console.log("value: " + categories[category].categoryName);
                option.text = categories[category].categoryName;
                catList.add(categories[category].categoryName);
            }
        });

The HTML content

<select id="categories" class="form-control"></select>

The error:

(index):116 Uncaught TypeError: Failed to execute 'add' on 'HTMLSelectElement': The provided value is not of type '(HTMLOptionElement or HTMLOptGroupElement)'
at Object.<anonymous> ((index):116)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at y (jquery.min.js:4)
at XMLHttpRequest.c (jquery.min.js:4)

Any help is appreciated.

Retro
  • 113
  • 13
  • Possible duplicate of [How can I use JSON data to populate the options of a select box?](https://stackoverflow.com/questions/5918144/how-can-i-use-json-data-to-populate-the-options-of-a-select-box) – Nitin Dhomse Nov 30 '17 at 06:16

2 Answers2

1

try this

$.get("http://localhost:8080/cc/sc/cat").done(function(categories) {
            for (category in categories){
              $('#categories').append('<option>'+categories[category].categoryName+'</option>')
            }
        });
laiju
  • 1,353
  • 10
  • 17
0

You have to wrap your option to generate out data for your select as below example.

function generateSelect(){
  var categories = [{id: 1, categoryName: "General Discussion"},{id: 2, categoryName: "Cleaning and Repairs"}];

     var catList = document.getElementById("categories");
  for (var a = 0; a< categories.length; a++){
        var option = document.createElement("option");
         option.value = categories[a].id;
         option.text = categories[a].categoryName;
        catList.append(option);
    }
}
i3lai3la
  • 980
  • 6
  • 10