HTML select option to be captured from Google Spreadsheet

前端 未结 3 596
闹比i
闹比i 2020-12-11 10:58

I have been spending days to get over this but no luck.

I have a html page in Google script whereby I want a dropdown list - this is achieved as follows



        
相关标签:
3条回答
  • 2020-12-11 11:19

    This is an adaptation of the technique demonstrated in the Html Service: Best Practices documentation.

    Code.gs

    function doGet() {
      var template = HtmlService
                     .createTemplateFromFile('DynamicList');
    
      var htmlOutput = template.evaluate()
                       .setSandboxMode(HtmlService.SandboxMode.NATIVE);
    
      return htmlOutput;
    }
    
    function getListOptions() {
      // In production code, get an array of options by
      // reading a spreadsheet.
      var options = ['Saab','Opel','Audi'];
    
      return( options );
    }
    

    DynamicList.html

    <div>
      <select id="optionList">
        <option>Loading...</option>    
      </select>
    
    </div>
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
    </script>
    <script>
    // This code in this function runs when the page is loaded.
    $(function() {
      google.script.run.withSuccessHandler(buildOptionList)
          .getListOptions();
    });
    
    function buildOptionList(options) {
      var list = $('#optionList');
      list.empty();
      for (var i = 0; i < options.length; i++) {
        list.append('<option value="' + options[i].toLowerCase() + '">' + options[i] + '</option>');
      }
    }
    </script>
    
    0 讨论(0)
  • 2020-12-11 11:24

    You can take a look at the documentation, specifically, Pushing section variables to templates, insurance can be useful.

    0 讨论(0)
  • 2020-12-11 11:37

    To display the elements in the array instead of the array object itself, you need to include the DATA array inside Scriptlet tags.And I see no requirement to use a 2-dimensional array. The correct syntax should be:

    <?
     var sheet   =  SpreadsheetApp.openById(0Avt7ejriwlxudGZfV2xJUGJZLXktQ2RhQU1ugtgtaXc").getSheetByName("MRF Tab");
      var lastRow = sheet.getLastRow();  
      var myRange = sheet.getRange("C3:C"+lastRow); 
      var data    = myRange.getValues();
      ?>
    <div>
      <select>
        <? for (var i = 0; i < data.length; ++i) { ?>
          <option><?!= data[i] ?></option>
        <? } ?>
      </select>
    </div>
    

    And its really a bad idea to mix data-fetching code & html UI code within a template. You should use separate gs and html files & apply the optimizations as Mogsdad has suggested.

    0 讨论(0)
提交回复
热议问题