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

Google Place API自动完成如何实现Formidable Forms邮政编码自动填充

问题排查与修复方案

根因分析

postal_code字段填充异常主要有两个常见原因:

  • Formidable Forms生成的邮编字段ID与脚本中拼接的field_postal_code不匹配:该插件默认生成的邮编字段ID通常为field_zip,或是绑定了自定义数字ID,与脚本默认匹配规则不符
  • 原有脚本的地址组件匹配逻辑存在缺陷:Google Places API返回的地址组件types是数组,postal_code可能不是数组第一位的元素,仅取types[0]匹配会漏掉该字段

修复步骤

第一步:确认邮编字段的实际ID

在浏览器打开表单页面,按F12打开开发者工具,用元素选择器点选邮编输入框,查看元素的id属性值,可直接修改脚本对应逻辑,也可以在Formidable Forms的字段设置里将邮编字段的ID改为postal_code,保持和脚本匹配。

第二步:修改地址填充逻辑

将原有fillInAddress函数替换为以下代码,修复组件匹配规则:

function fillInAddress() {
  var place = autocomplete.getPlace();
  // 先清空原有字段值避免残留
  for (var addressType in componentForm) {
    var field = document.getElementById('field_' + addressType);
    if (field) field.value = '';
  }
  // 遍历地址组件,检查整个types数组匹配规则
  for (var i = 0; i < place.address_components.length; i++) {
    var component = place.address_components[i];
    // 遍历当前组件所有type,匹配我们需要的字段
    for (var j = 0; j < component.types.length; j++) {
      var addressType = component.types[j];
      if (componentForm[addressType]) {
        var val = component[componentForm[addressType]];
        var targetField = document.getElementById('field_' + addressType);
        // 额外判断字段是否存在,不存在不执行赋值避免报错
        if (targetField) {
          targetField.value = val;
          // 如果需要拼接邮编后缀,可开启以下注释
          // if (addressType === 'postal_code' && component.types.includes('postal_code_suffix')) {
          //   targetField.value += '-' + component['short_name'];
          // }
          break;
        }
      }
    }
  }
}

可选适配:如果邮编字段ID确实是field_zip

可直接修改componentForm配置,新增字段映射即可,示例:

var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};
// 赋值时替换字段ID即可,也可直接修改componentForm的映射规则,将postal_code对应到field_zip

内容的提问来源于stack exchange,提问作者Umais Bin Sajjad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:48:03