1

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.

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.