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
相关产品推荐
相关产品推荐

