簡體   English   中英

使用 Google 表格中的數據在 Google Apps 腳本中自動完成

[英]Autocomplete in Google Apps Script with data from Google Sheets

我正在嘗試使用 Google Apps 腳本創建一個表單,其中的字段允許自動完成。 在我創建的其他 forms 中,我已經能夠從谷歌工作表中提取一系列選項,並使用它們來填充下拉列表,所以我必須認為可以通過自動完成過程來做同樣的事情。

我公然從 w3schools 復制了這個示例,只要我在 javascript 中聲明數組(如示例中所做的那樣),它就可以完全按照需要工作。 但我無法弄清楚的是如何使用從我的谷歌表中提取的選項填充數組。

這是我開始的地方:

var PMOSupport;

$(function() {
   google.script.run.withSuccessHandler(buildDropDowns)
   .getPMOSupport();
});


function buildDropDowns(data) {
  PMOSupport = data;
  console.log(PMOSupport);
}


function autocomplete(inp, arr) {
  console.log("ENTER AUTO");
  var currentFocus;
  inp.addEventListener("input", function(e) {
  // all of the remaining code is direct from the w3schools example
  // I'm cutting it from here for brevity, 
  // and because I know this works, when using the declared array below
  });
}

var countries = ["Afghanistan","Albania","Algeria","Andorra"];

// this line works fine, when using the array declared above    
// autocomplete(document.getElementById("myInput"), countries);  

// this line does not work, when trying to use the array populated from the google sheet
autocomplete(document.getElementById("myInput"), PMOSupport);  

當我運行它時,頁面會創建,並且在我輸入輸入字段后,我會在控制台中收到一條消息:

`Uncaught TypeError: Cannot read property 'length' of undefined`
    at HTMLInputElement.<anonymous> (<anonymous>:32:28)

當我研究這個時,它是說'arr'參數(PMOSupport)沒有被填充。 這就是為什么我添加了 2 個 console.log 行,以查看事情發生的順序。 當我打開頁面時,首先記錄“ENTER AUTO”,然后是 State 從 Idle 變為 Busy 並從 Busy 變為 Idle(當它調用 getPMOSupport() 時),然后 PMOSupport 數組在控制台中記錄(也證明我實際上是從工作表中獲取正確的數據)。 很明顯,它在調用 google.script.run.withSuccessHandler(buildDropDowns).getPMOSupport() 部分之前輸入了 function autocomplete(),這就是未定義“arr”參數的原因。

我嘗試了各種方法將其從$(function() … });中取出。 塊,嘗試在 autocomplete() function 運行之前填充 PMOSupport 數組。 我所做的一切似乎都沒有奏效。

我確信這很簡單,並且是由我隨着時間的推移養成的壞習慣造成的(我不是開發人員,我只是為我的團隊拼湊一些東西)。 但任何幫助將不勝感激。

您需要在異步代碼返回后調用autocomplete 因此,您需要從回調中調用它。

function buildDropdowns(data, userObject) {
  // probably you should indicate in data which field these data is for, or use
  // the userObject parameter in the google.script.run API
  autocomplete(document.getElementById("myInput"), data); 
}

或者(我沒有也不會查看 w3schools 代碼),最初將您的PMOSupport聲明為 const 數組,然后將回調中的條目添加到其中(而不是重新分配它)。 這樣,變量就不是未定義的,它在開始時只是空的。 根據自動完成代碼的實現,這可能適合您,也可能不適合您。

const PMOSupport = [];
....
function buildDropdowns(data) {
  PMOSupport.push(...data);
  // or
  // Array.prototype.push.apply(PMOSupport, data);
}

暫無
暫無

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

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