You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script Web应用:下拉选单联动填充输入框问题求助

解决方案

1. 后端脚本(Code.gs)

负责从谷歌表格读取数据,接收前端传入的门店名称,返回匹配的公司名称:

function getSociedadByLocal(localName) {
  const spreadsheetId = "XXXXXXXXX"; // 替换为你的谷歌表格ID
  const sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName("DB_LOCALES");
  const dataRange = sheet.getRange("B:O").getValues();
  
  // 遍历B列匹配门店名称,返回对应O列值
  for (const row of dataRange) {
    if (row[0] === localName) {
      return row[13]; // B列对应数组索引0,O列对应索引13
    }
  }
  return ""; // 无匹配时返回空字符串
}

2. 前端HTML代码

负责监听下拉选单的变化事件,调用后端函数并更新输入框内容:

<!-- 门店下拉选单 -->
<select id="id-local">
  <option value="">请选择门店</option>
  <!-- 可根据需求动态加载或静态添加门店选项 -->
</select>

<!-- 公司名称输入框 -->
<input type="text" id="sociedad-local" readonly>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const localSelect = document.getElementById('id-local');
  
  localSelect.addEventListener('change', function() {
    const selectedLocal = this.value;
    const sociedadInput = document.getElementById('sociedad-local');
    
    if (!selectedLocal) {
      sociedadInput.value = '';
      return;
    }
    
    // 通过google.script.run调用后端函数
    google.script.run
      .withSuccessHandler(function(sociedad) {
        sociedadInput.value = sociedad;
      })
      .withFailureHandler(function(error) {
        console.error('获取数据失败:', error);
        alert('加载公司名称出错,请重试');
      })
      .getSociedadByLocal(selectedLocal);
  });
});
</script>

核心逻辑说明

  • 后端.gs脚本运行在Google服务器环境中,只能调用Google服务(如SpreadsheetApp),无法访问浏览器DOM(这是你之前在.gs里用document.getElementById报错的原因)。
  • 前端HTML中的JS运行在浏览器里,必须通过google.script.run作为桥梁调用后端函数,再通过withSuccessHandler接收返回结果并更新页面元素。
  • 部署Web应用时,需确保表格权限与Web应用权限匹配,避免出现访问权限错误。

内容的提问来源于stack exchange,提问作者Fabrisimo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:43:26