为单选框添加JS函数:选中X显示纠正区域但切换时无false日志
问题分析与解决
问题核心是仅带X的单选按钮绑定了onclick事件,带对勾的按钮没有绑定触发逻辑。当切换到对勾按钮时,不会执行checkMe函数,自然不会触发else分支的代码(输出false+隐藏纠正区域);同时页面初始化阶段也未执行函数,初始状态也不会输出false。
修复方案
- 给带对勾的单选按钮添加
onclick="checkMe()",确保切换任意选项时都会触发函数。 - 页面加载完成后自动调用一次
checkMe(),初始化区域显示状态并输出初始日志。
修改后的完整代码
JavaScript 代码
function checkMe() { var cb = document.getElementById("registration-danger"); var ca = document.getElementById("correctiveAction"); if (cb.checked == true) { ca.style.display = "block"; console.log('true'); } else { ca.style.display = "none"; console.log('false'); } } // 页面加载时初始化状态 window.onload = function() { checkMe(); };
HTML 代码(仅修改按钮绑定部分)
<!--Registration Line--> <div class="accordion-body vehicleBody border border-light-subtle"> <h3 id="registration" class="mx-3">Current / Valid Vehicle Registration <span> <input onclick="checkMe()" type="radio" class="btn-check" name="registration" id="registration-success" autocomplete="off" > <label class="btn btn-outline-success rounded-circle" for="registration-success"><i class="fa-solid fa-check"></i></label> <input onclick="checkMe()" type="radio" class="btn-check" name="registration" id="registration-danger" autocomplete="off" /> <label class="btn btn-outline-danger rounded-circle ms-3" for="registration-danger"><i class="fa-solid fa-x"></i></label> </span> </h3> <div class="ms-3" id="correctiveAction"> <p class="text-center" style="font-weight: 400; padding: 10px; color: crimson; text-decoration: underline;">Corrective Action Required!</p> <div class="form-floating correctiveAction"> <textarea class="form-control" id="floatingTextarea2" style="height: 100px"></textarea> <label for="floatingTextarea2">Please determine appropriate corrective action.</label> </div> </div> </div>
效果验证
- 页面加载完成后,自动执行
checkMe(),默认未选中X按钮,控制台输出false,纠正区域隐藏。 - 点击X按钮,控制台输出
true,纠正区域显示;切换回对勾按钮,控制台输出false,纠正区域隐藏。
内容的提问来源于stack exchange,提问作者tDeanKR
相关产品推荐
相关产品推荐

