How to Populate HTML Service Select Options from Range in Google Sheet?

When initializing optionsHTML that should be direct assignment, not +=. Instead, use the += in the for loop as you’ll otherwise be replacing the contents of optionsHTML rather than appending to it.

function getVendors() {
  var active = SpreadsheetApp.getActive();
  var sheet = active.getSheetByName("Vendor Database");
  var lastRow = sheet.getLastRow();
  var myRange = sheet.getRange("A2:A" + lastRow); 
  var data    = myRange.getValues();
  var optionsHTML = "";
  for (var i = 0; i < data.length; i+=1) {
    optionsHTML += '<option>' + data[i][0] + '</option>';
  };
  return optionsHTML;
}

Make sure you’re correctly evaluating the HTML. Because of the way you’ve set this up, you need to treat your HTML file (I’m assuming it’s called Index.html) as a template.

function doGet() {
  return HtmlService.createTemplateFromFile('Index').evaluate()
}

Finally, in the HTML file, looks like you’re using incomplete anchors. Should be <?!= ... ?> and then call the function directly. (Also, remove the surrounding <option></option> tags as getVendors() already provides those.)

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
</head>
<body>
  <form>
    <div>
      <select>
        <?!= getVendors(); ?>
      </select>
    </div>
  </form>
</body>
</html>

Once you have that working, and if it makes sense to put some more time and care into this, refactor to follow the best practices and load data asynchronously, not in templates by using a client-side script inside the HTML as mentioned by @Cooper.

Leave a Comment