单选按钮选择No时显示空白的问题修复咨询
问题描述
我设置了4组Yes/No单选按钮,选择Yes选项时可正常显示值'YES',但选择No选项时仅显示空白。请问该如何修复此问题?
相关HTML代码
<div id='testtwo' style="display:block;"> <label class="control-label col-sm-4" for="pnl">Is the packing properly vacuum sealed? :</label> <div class="col-sm-4" style="margin-top:19px;"> <p class="form-control-static" style="margin-top: -7px;display: inline-flex;color: darkslategrey;"> <input type="radio" name="pkyes" value="YES"> <label for="pkyes" style="margin-left: 6px; margin-top: 8px;">YES</label><br> <input type="radio" name="pkyes" value="NO" style="margin-left: 16px;"> <label for="pkno" style="margin-left: 6px; margin-top: 8px;">NO</label><br> </p> </div> </div>
对应的JavaScript代码
var testasd=document.querySelector('input[type=radio][name=pkyes]'); if(testasd.checked == false ){ var pk = ''; }else { var pk = testasd.value; }
问题原因
你用document.querySelector('input[type=radio][name=pkyes]')只会选中第一个匹配到的单选按钮(也就是YES选项)。当选择NO时,第一个单选按钮处于未选中状态,代码会进入if分支把pk设为空字符串,所以显示空白。
修复方案
方案1:直接获取选中的单选按钮
利用:checked伪类直接定位被选中的选项,不管是YES还是NO:
// 直接获取被选中的单选按钮 var testasd = document.querySelector('input[type=radio][name=pkyes]:checked'); // 如果有选中项就取它的值,否则设为空 var pk = testasd ? testasd.value : '';
方案2:遍历所有单选按钮判断
先获取同name的所有单选按钮,逐个检查是否被选中:
var radios = document.querySelectorAll('input[type=radio][name=pkyes]'); var pk = ''; for (var i = 0; i < radios.length; i++) { if (radios[i].checked) { pk = radios[i].value; break; // 找到选中项后停止遍历,提升效率 } }
额外优化:修复HTML标签关联问题
你的<label>标签的for属性没有对应单选按钮的id,导致点击标签无法选中对应的单选按钮。建议补上id属性:
<div id='testtwo' style="display:block;"> <label class="control-label col-sm-4" for="pnl">Is the packing properly vacuum sealed? :</label> <div class="col-sm-4" style="margin-top:19px;"> <p class="form-control-static" style="margin-top: -7px;display: inline-flex;color: darkslategrey;"> <input type="radio" name="pkyes" id="pkyes" value="YES"> <label for="pkyes" style="margin-left: 6px; margin-top: 8px;">YES</label><br> <input type="radio" name="pkyes" id="pkno" value="NO" style="margin-left: 16px;"> <label for="pkno" style="margin-left: 6px; margin-top: 8px;">NO</label><br> </p> </div> </div>
内容的提问来源于stack exchange,提问作者Travis Sloap
相关产品推荐
相关产品推荐

