如何使用JavaScript获取用户选中的单选按钮值
获取Bootstrap单选按钮选中值的实现方案
先看修正后的HTML结构(修复了label的for属性不匹配问题):
<div class="d-flex justify-content-center"> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="5"> <label class="form-check-label" for="inlineRadio1">5 stars</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="4"> <label class="form-check-label" for="inlineRadio2">4 stars</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="3"> <label class="form-check-label" for="inlineRadio3">3 stars</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio4" value="2"> <label class="form-check-label" for="inlineRadio4">2 stars</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio5" value="1"> <label class="form-check-label" for="inlineRadio5">1 star</label> </div> </div>
下面提供两种常用的JavaScript实现方式:
1. 实时监听选中变化(推荐)
利用事件委托监听父容器的change事件,无需给每个单选按钮单独绑定事件,更高效简洁:
// 监听父容器的change事件 document.querySelector('.d-flex.justify-content-center').addEventListener('change', function(e) { // 确认触发事件的是目标单选按钮 if (e.target.matches('.form-check-input[type="radio"]')) { const selectedStar = e.target.value; console.log('选中的星级:', selectedStar); // 此处可添加业务逻辑,比如更新页面显示、提交数据等 } });
2. 按需获取当前选中值
如果不需要实时监听,而是在特定操作(如点击提交按钮)时获取值,可直接查询选中元素:
// 获取当前选中的单选按钮 const checkedRadio = document.querySelector('input[name="inlineRadioOptions"]:checked'); if (checkedRadio) { const selectedValue = checkedRadio.value; console.log('当前选中星级:', selectedValue); } else { console.log('未选中任何星级'); }
注意事项
原HTML中最后两个label的for属性与对应input的id不匹配,已在上方代码中修正,这样点击标签也能选中对应的单选按钮,保证交互逻辑正常。
内容的提问来源于stack exchange,提问作者Dhenhice
相关产品推荐
相关产品推荐

