Eddie Taliaferro II
Eddie Taliaferro II

Reputation: 185

Selecting an OPTION from a SELECT list made from a FOR Loop

Just need some more help with a program I need to build for a job interview >.< For the overall project, I need the user to be able to select a breed a dogs, which is provided through an api. Its in a dropdown/select menu with options. Problem is, I can't seem to figure out a way to specify which option/breed. When I click an option, all I get is the very last option on the list. I am probably missing something very simple here ahhhhhhh:

var showcase = document.getElementById('showcase');

var select = document.getElementById('select-bar');

var request = new XMLHttpRequest();

// Get data from API endpoint
request.open('GET', 'https://dog.ceo/api/breeds/list', true);

request.onload = function () {
var data = JSON.parse(this.response);
var breeds = data.message;

if (request.status >= 200 && request.status < 400 ) {
 for (var i = 0; i < breeds.length; i++) {

   var opt = document.createElement('option');
   opt.innerHTML = breeds[i];
   opt.value = breeds[i];
   select.appendChild(opt);

}
select.addEventListener("change", function(event) {
  console.log(opt); })
 }
}

request.send();

I am such a noob with APIs and working with Loops/Arrays ahhh. Help :(

Upvotes: 0

Views: 193

Answers (2)

FDavidov
FDavidov

Reputation: 3675

You may solve this in a number of ways, the simplest is to add an onClick event to each entry that will invoke a function and pass as a parameter the breed-ID.

A nice alternative would be to use a framework, like AngularJS (which is the one I use). This, however, would require you to go through some learning.

Upvotes: 0

brk
brk

Reputation: 50291

Add the addEventListener to select element outside the if loop.Also to get the selected element use event.target.value

var showcase = document.getElementById('showcase');
var select = document.getElementById('select-bar');
var request = new XMLHttpRequest();

// Get data from API endpoint
request.open('GET', 'https://dog.ceo/api/breeds/list', true);

request.onload = function() {
  var data = JSON.parse(this.response);
  var breeds = data.message;

  if (request.status >= 200 && request.status < 400) {
    for (var i = 0; i < breeds.length; i++) {

      var opt = document.createElement('option');
      opt.innerHTML = breeds[i];
      opt.value = breeds[i];
      select.appendChild(opt);

    }
  }
}
request.send();

select.addEventListener("change", function(event) {
  console.log(event.target.value);
})
<select id="select-bar"></select>

Upvotes: 1

Related Questions