-2

Hello I am trying to populate a select list using JSON and I am not getting any console errors however the list is not getting populated at all.

This is my html code

    <select id="player_dropdown1">
    </select>

This is my javascript code

    var request = new XMLHttpRequest()

    request.open('GET','https://cors- 
anywhere.herokuapp.com/https://fantasy.premierleague.com/api/bootstrap-static/' , true)

request.onload = function() {

let dropdown = document.getElementById('player_dropdown1');
dropdown.length = 0;


let defaultOption = document.createElement('option');
defaultOption.text = 'Select a player';

dropdown.add(defaultOption);
dropdown.selectedIndex = 0;

   var data = JSON.parse(this.response);

if (request.status >= 200 && request.status < 400) {

        let option;

        for (let i = 0; i < data.length; i++) {
          option = document.createElement('option');
          option.text = data.elements[i].firstname + data.elements[i].secondname;
          option.value = data.elements[i].secondname;
          dropdown.add(option);
        }
       } else {

      }   
console.log(data);

}

request.onerror = function() {
  console.error('An error occurred fetching the JSON');
};


request.send(); 

I am not sure why the dropdown list is not getting populated. The json is getting parsed successfully to the console.

Samuel Liew
  • 68,352
  • 105
  • 140
  • 225

1 Answers1

1

If you have a document.getElementById(ID) returning null or undefined on a very obviously defined ID, it is because your DOM element having the ID in question does not exist when the javascript is loaded.

You have two solutions:
- Include the script after the DOM element having the ID is declared
- Delay the execution of your code until the document is loaded, see this question for plain javascript.

I would personally choose the first solution if there are no "obligations" (such as code pattern) to include the javascript before the end of the document. This is going to save you the lines of codes of the event handlers and performance-side it does not add any more operations during the loading of the webpage.

Noah Boegli
  • 558
  • 6
  • 21
  • I managed to fix this problem, however the list is not getting populated still. – Sahil Chabria ramchandani Mar 06 '20 at 12:59
  • Please do not change your question by that much, you are making it unusable for future users experiencing the same issues. If you had to change the content of the question it is maybe because your question was not clear/specific enough at the beginning. Please read [how do I ask a good question](https://stackoverflow.com/help/how-to-ask) – Noah Boegli Mar 06 '20 at 13:02