簡體   English   中英

如何使用 Google 工作表中的值填充選擇元素的下拉列表?

[英]How to populate dropdown list at selection element with values from Google sheet?

我有一個帶有自定義 HTML 表格的 Google 表格。 表單包含<selection>元素。 像這樣

 <select id="category_name" name="category_name" class="control" style="width:150px;height:20px;margin:10px 0 10px 0;"> <option value="" selected></option> </select>

我從工作表中獲取值

 function getCategory() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const sh = ss.getSheetByName(SHEET_NAME); let list = sh.getRange(2, 1, sh.getLastRow() - 1).getValues(); return list; }

然后我用 HTML 文件中的預期值填充這個選擇

 (function () { google.script.run.withSuccessHandler( function (selectList) { var select = document.getElementById("category_name"); for( var i=0; i<selectList.length; i++ ) { var option = document.createElement("option"); option.val = selectList[i][0]; option.text = selectList[i][0]; select.add(option); } } ).getCategory(); }());

看起來列表填充得很好,但是當我從選擇中選擇一些項目時,它在表單提交后返回空白值。 我錯在哪里以及如何解決?

問題:

您沒有正確設置<option>val不是有效屬性。 因此,不會向每個<option>添加任何值,並且不會提交它們。

解決方案:

像這樣設置選項值:

option.value = selectList[i][0];

使用選項構造函數:

當然,使用 Option 構造函數也可以:

var option = new Option(selectList[i][0], selectList[i][0]);

參考:

我經常使用這個:

function updateSelect(vA,id){
  var id=id || 'sel1';
  var select = document.getElementById(id);
  select.options.length = 0; 
  for(var i=0;i<vA.length;i++) {
    select.options[i] = new Option(vA[i],vA[i]);//Option(text, value);
      }
    }

新選項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM