amnoyes97
amnoyes97

Reputation: 23

Populate a dropdown using jQuery

I am trying to populate a drop down using with the following JSON data:

[
  {
    "id": "1",
    "name": "Unknown"
  },
  {
    "id": "2",
    "name": "Chrome"
  },
  {
    "id": "3",
    "name": "Firefox"
  },
  {
    "id": "4",
    "name": "Internet Explorer"
  },
  {
    "id": "5",
    "name": "Edge"
  },
  {
    "id": "6",
    "name": "Safari"
  },
  {
    "id": "7",
    "name": "Mobile Chrome"
  },
  {
    "id": "8",
    "name": "Mobile Safari"
  },
  {
    "id": "9",
    "name": "Opera"
  }
]

Here is my code:

$(document).ready(function () {
  $.getJSON("http://www.randyconnolly.com/funwebdev/services/visits/browsers.php", function(results){
      var $el = $("#filterBrowser");
      $el.empty(); // remove old options
      $el.append($("<option></option>")
      .attr("value", '').text('Please Select'));
      
      $.each(results, function (index, value) {
          $el.append($("<option></option>")
          .attr("value", value).text(value));

        });
    });
});

The dropdown is being populated incorrectly, and it's returning

[object Object]

rather than "Unknown,Chrome,Firefox,Internet Explorer, and so on.

Upvotes: 1

Views: 45

Answers (1)

charlietfl
charlietfl

Reputation: 171700

The value in your each is an object so you need the specific property names (id & name) to pass to value and text of the new options

var $el = $("#filterBrowser");
$el.empty(); // remove old options
$el.append($("<option></option>")
  .attr("value", '').text('Please Select'));

$.each(results, function(index, value) {
  $el.append($("<option></option>")
    .attr("value", value.id).text(value.name));
                  // ^^ id              ^^ name

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="filterBrowser"></select>

<script>
 const results=[{id:"1",name:"Unknown"},{id:"2",name:"Chrome"},{id:"3",name:"Firefox"},{id:"4",name:"Internet Explorer"},{id:"5",name:"Edge"},{id:"6",name:"Safari"},{id:"7",name:"Mobile Chrome"},{id:"8",name:"Mobile Safari"},{id:"9",name:"Opera"}];
</script>

Upvotes: 1

Related Questions