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

点击产品列表指定按钮能否自动勾选WordPress wpforms表单对应复选框?

实现方案

步骤1:修改产品列表按钮代码,绑定产品名称

你需要先把产品标题存储到Check按钮的自定义属性中,用于后续和表单复选框做匹配,修改后的产品列表代码如下:

<div class="news-text-box">
  <span class="news-date"><?php the_sub_field('pbauthor'); ?></span>
  <span class="news-title"><?php the_sub_field('pbtitle'); ?></span>
  <span class="news-text"><?php the_sub_field('pbdetail'); ?></span>
  <!-- 新增data-product-title属性存储产品标题,和复选框value做匹配 -->
  <span class="checkbutton" data-product-title="<?php echo esc_attr(get_sub_field('pbtitle')); ?>">Check</span>
</div>

注意要保证这里存储的产品标题和wpforms复选框设置的value值完全一致,无多余空格、特殊符号差异。

步骤2:添加交互JS代码

将以下JS代码添加到站点中即可实现点击按钮自动勾选对应复选框的效果,代码可放在WordPress后台「外观」→「自定义」→「额外JS」区域,也可以放在当前主题的footer.php文件的</body>标签之前:

document.addEventListener('DOMContentLoaded', function() {
  // 绑定所有产品Check按钮的点击事件
  document.querySelectorAll('.checkbutton').forEach(btn => {
    btn.addEventListener('click', function() {
      // 获取当前产品的名称
      const product = this.dataset.productTitle;
      // 匹配表单中对应产品的复选框
      const targetCheckbox = document.querySelector(`#wpforms-187-field_28 input[value="${product}"]`);
      
      if(targetCheckbox) {
        // 切换勾选状态,如需强制勾选可改为 targetCheckbox.checked = true
        targetCheckbox.checked = !targetCheckbox.checked;

        // 可选功能:点击后自动展开咨询表单,将下方选择器替换为你顶部咨询按钮的实际选择器即可
        // const consultToggle = document.querySelector('.咨询按钮的类或ID');
        // consultToggle && consultToggle.click();

        // 可选功能:点击后平滑滚动到表单位置
        // targetCheckbox.scrollIntoView({behavior: 'smooth', block: 'center'});
      }
    });
  });
});

注意事项

  • 如果你的wpforms表单ID不是187,或者复选框字段ID不是28,需要对应修改代码中#wpforms-187-field_28的部分
  • 如果需要点击按钮后直接跳转到表单提交,可自行启用代码中注释的滚动、展开表单逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:54:08