首页 > 解决方案 > 谷歌脚本映射

问题描述

我试图在 Google Script 上使用映射在 City (id="city") 字段中输入一个值,并使用下面的脚本显示价格 (id="price")。下面的代码不起作用,也没有在价格文本框中提供任何结果。此外,是否可以执行多个条件?我的意思是价格将根据城市、产品和数量显示。我提供了下面的图片。谢谢!

  <script>
 
    document.getElementById("btn").addEventListener("click",getPrice);

    function getPrice(){
      vCity = document.getElementById("city").value;
      google.script.run.withSuccessHander(updatePrice).getAmount(vCity);

    }

    function updatePrice(myprice) {
      document.getElementById("price").value = myprice;
    }

  </script>

这是我的gs。

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile("page");
}


function getAmount(city) {
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1FhWlaXixXPxq8EnHICfVR207aIkxtkzOgvdvt3hHuuI/edit#gid=0");
  var ws = ss.getSheetByName("Pricing");
  var data = ws.getRange(1, 1, ws.getLastRow(),2).getValues();

  var cityList = data.map(function(r){ return r[0]; });
  var priceList = data.map(function(r){ return r[1]; });
  var position = cityList.indexOf(city);

  if(position > -1){
    return priceList[position];
  } else {
    return "Unavailable";
  }

图片

标签: javascriptgoogle-apps-scriptgoogle-sheetsmapping

解决方案


这对我有用。我将其作为对话框运行。我更改了工作表名称。

function launchmypricedialog() {
  let html = '<input type="text" id="city" placeholder="City" /><br /><input type="text" id="price" /><br /><input type="button" value="Click Me" id="btn"/><script>document.getElementById("btn").addEventListener("click",getPrice);function getPrice(){let vCity = document.getElementById("city").value;google.script.run.withSuccessHandler(updatePrice).getAmount(vCity);}function updatePrice(myprice) {console.log(myprice);document.getElementById("price").value = myprice;}</script>';
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'test');
}

function getAmount(city) {
  var ss = SpreadsheetApp.getActive();
  var ws = ss.getSheetByName("Sheet1");
  var data = ws.getRange(2, 1, ws.getLastRow()-1, 2).getValues();
  var cityList = data.map(function (r) { return r[0]; });
  var priceList = data.map(function (r) { return r[1]; });
  //console.log(city);
  //console.log(JSON.stringify(cityList));
  //console.log(JSON.stringify(priceList));
  var position = cityList.indexOf(city);
  //console.log(priceList[position]);
  if (position > -1) {
    return priceList[position];
  } else {
    return "Unavailable";
  }
}

这是我的数据

COL1 COL2
城市1 12
城市2 2
城市3 24
城市4 18
城市5 14
城市6 3
城市7 17
城市8 5
城市9 29
城市10 24
城市 11 8
城市12 26
城市13 15
城市 14 25
城市 15 0
城市16 25
城市 17 17
城市18 11
城市 19 22
城市20 10
城市21 16
城市22 0
城市23 6
城市24 22
城市25 15
城市26 11
城市27 13
城市28 14
城市29 22
城市30 24

我的对话框:

在此处输入图像描述


推荐阅读