0

I've been googling for the past hour and can't seem to find any posts relevant to my question.

I'm trying to loop over all the results from an API request and map it accordingly as a select option.

Here's my code:

<script>

var urlRoot = 'https://newsapi.org/v2/';
var sourceList = 'sources?';
var apiLanguage = 'language=en&';
var apiKey = 'XXX';

$(document).ready( function() {
  $.ajax({
    url: urlRoot + sourceList + apiLanguage + apiKey,
    method: 'GET',
    dataType: 'json',
    }).then(function(data) {
        console.log(data.sources);
        $.each(data, function(sources, name) {
          $('#source-selection').append(name);
        })
      });
    });
</script>

<select>
  <option> Show Everything </option>
  <option id="source-selection"></option>
</select>

The API returns the sources as an array of ~80.

Thanks in advance and sorry for bad english.

Shaun Y
  • 41
  • 1
  • 8
  • I suppose you want do this? https://stackoverflow.com/questions/740195/adding-options-to-a-select-using-jquery#14447147 . If so, `mySelect` id is on ` – MarshalSHI Dec 11 '17 at 01:57

1 Answers1

3

Because you want to add each item in data.sources as an option in your select, you first need to iterate over data.sources and then append each item to select. Also, make sure you add a value attribute to each option in the list:

Edit: For security, use val and text to set the properties on a new option element directly:

<script>

var urlRoot = 'https://newsapi.org/v2/';
var sourceList = 'sources?';
var apiLanguage = 'language=en&';
var apiKey = 'XXX';

$(document).ready( function() {
  $.ajax({
    url: urlRoot + sourceList + apiLanguage + apiKey,
    method: 'GET',
    dataType: 'json',

    }).then(function(data) {

        console.log(data.sources);

        $.each(data.sources, function(index, value) {

          var $option = $("<option></option>");

          $option.val(value);
          $option.text(value);

          $('#source-selection').append($option);

        });
      });
    });
</script>

<select id="source-selection">
  <option value="everything">Show Everything </option>
</select>
Christian Santos
  • 5,386
  • 1
  • 18
  • 24
  • Hi Christian, thank you for your response. Could you elaborate on the (index, value) portion of that snippet? And also, it's showing all the options as "object Object" right now. Thank you. – Shaun Y Dec 11 '17 at 02:03
  • 1
    It's extremely important that you escape your data when injecting it into HTML. As is right now, you're opening yourself up to a broken application or even some security issues. – Brad Dec 11 '17 at 02:06
  • Thanks @Brad, made an edit to code to let jQuery handle the escaping. – Christian Santos Dec 11 '17 at 02:16