You need to enable JavaScript to run this app. Shopify场景下如何获取被选中radio单选按钮的ID值并赋值给输入框ID属性
优惠活动
大模型
产品
解决方案
定价
更多

Shopify场景下如何获取被选中radio单选按钮的ID值并赋值给输入框ID属性

问题原因

你使用的{%if radio.checked='checked'%}属于服务端模板语法,仅在页面首次渲染时执行,无法响应浏览器端用户切换单选框的交互动作,因此无法动态更新输入框的ID属性,需要通过JavaScript实现交互逻辑。

完整实现代码
<input type="radio" id="male" name="gender" value="male" checked>
<label for="male">男</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">女</label><br>

<!-- 初始ID和默认选中的radio保持一致 -->
<input type="text" id="male" class="">

<script>
// 绑定单选框切换事件
document.querySelectorAll('input[name="gender"]').forEach(radio => {
  radio.addEventListener('change', function() {
    if (this.checked) {
      // 将选中radio的ID赋值给文本输入框
      document.querySelector('input[type="text"]').id = this.id
    }
  })
})
</script>
效果验证

打开浏览器控制台,切换单选框选项,即可看到文本输入框的ID属性会同步更新为当前选中单选框的ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 18:15:07