如何在HTML表单单选框中添加可编辑的Other(其他)选项?
实现思路
你需要给单选按钮绑定状态联动逻辑,核心规则是:只有当Other单选框被选中时,对应的自定义输入框才允许编辑,未选中状态下输入框默认禁用避免误输入。
修改后完整代码
<!-- 单选组统一加相同name属性确保是同一组单选题 --> <div class="radio-group"> <label> <input type="radio" name="question1" value="answer1"> answer1 </label> <br> <label class="other-option"> <input type="radio" name="question1" value="other"> Other: </label> <!-- 其他选项对应的自定义输入框,默认禁用 --> <input type="text" name="question1_other" id="otherInput" disabled placeholder="请输入自定义答案"> </div> <style> /* 可选样式调整,对齐输入框 */ .radio-group { display: flex; flex-direction: column; gap: 8px; } .other-option { display: inline-flex; align-items: center; gap: 4px; } #otherInput { margin-left: 4px; padding: 2px 4px; } /* 禁用状态下的输入框样式,提示不可编辑 */ #otherInput:disabled { background-color: #f0f0f0; border: 1px solid #ddd; cursor: not-allowed; } </style> <script> const otherRadio = document.querySelector('input[name="question1"][value="other"]'); const otherInput = document.getElementById('otherInput'); // 监听单选组变化 document.querySelectorAll('input[name="question1"]').forEach(radio => { radio.addEventListener('change', () => { // 选中Other时启用输入框,否则禁用并清空内容 otherInput.disabled = !otherRadio.checked; if (!otherRadio.checked) { otherInput.value = ''; } }); }); </script>
使用说明
- 提交表单时如果
other单选框为选中状态,取question1_other字段的值作为该题的答案即可,否则取question1字段的选中值。 - 你可以按照自己的需求继续调整CSS样式匹配页面整体设计。
内容的提问来源于stack exchange,提问作者Ismail86
相关产品推荐
相关产品推荐

