0

I have a page with a hidden drop-down box that appears when a checkbox is ticked via a JavaScript inner.HTML = command. As I'm aware I wouldn't be able to populate this from a document.onload function, I've got a <div>, that I'll be setting to style="display:none" when I have this working, where I have a drop-down box in for the options to be populated to, however I'm getting the error message 'Unable to set property 'innerHTML' of undefined or null reference' when attempting to do this. Is a <select> tag not able to have an ID or innerHTML value given to it?

Code is below:

var systemOptions = [];
var system = document.getElementById("systemstemp");
document.onload = getSystems();

function getSystems() {
  $.ajax({
    url: ".../_api/web/lists/getbytitle('Application List')/items?$select=Title",
    type: "GET",
    headers: {"accept": "application/json;odata=verbose"},
    success: function (data) {
      systemOptions = data.d.results;
      for (var obj in systemOptions) {
        system.innerHTML = "<option value='" + systemOptions[obj].Title + "'>" + systemOptions[obj].Title + "</option>";
      }
    }
  });
}
<p><select id="systemstemp"></select></p>
systemOptions = [
  {Title: "Call Platform"},
  {Title: "CRM"},
  {Title: "Email"},
  {Title: "Monitoring"},
]
Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
  • You can see the solution here. `https://stackoverflow.com/questions/8674618/adding-options-to-select-with-javascript` – Madhu Magar Dec 12 '19 at 14:07

1 Answers1

1

The problem is that when you do:

document.onload = getSystems();

you're actually calling getSystems function immediately and not when document.onload fires. In order to run getSystems when onload triggers, set the function without parenthesis:

document.onload = getSystems;

or assign the function directly to the document.onload:

document.onload = function() {
  $.ajax({...});
}

EDIT

You should also use DOM API to create the select options like in this Q/A:

Adding options to select with javascript

Christos Lytras
  • 36,310
  • 4
  • 80
  • 113