如何动态隐藏JavaScript生成的单选按钮组中未选中的Removed按钮
解决动态生成单选按钮时隐藏Removed选项的问题
我看了你的代码,要实现「当Removed单选按钮未被选中时隐藏它,仅显示另外三个选项」的需求,咱们可以从初始化隐藏和动态切换显示状态两个方面来修改代码:
核心修改思路
- 初始化生成Removed选项时,判断当前是否选中它——如果没选中,直接隐藏对应的容器
- 给所有单选按钮添加
change事件监听,当用户切换选中状态时,动态控制Removed选项的显示/隐藏
修改后的完整代码
//Create the main RadioDiv and append radio options var radioQuestion = document.createElement("div"); radioQuestion.setAttribute("id", name + "RadioDiv"); fsRadio.appendChild(radioQuestion); //For each radio button option do the following for (var d = 0; d < optionList.length; d++) { var name = optionList[d].name; var value = optionList[d].value; //This creates the input field for each option var radioItem = document.createElement("input"); radioItem.setAttribute('type', "radio"); radioItem.setAttribute('name', flId); radioItem.setAttribute('id', flId + "_" + name); radioItem.setAttribute('value', value); if (status === null || status === "" || status === false || typeof status === 'undefined') { radioItem.setAttribute('class', "inactive-field"); radioItem.setAttribute('disabled', "disabled"); } else if (status === true) { radioItem.setAttribute('class', "active-field"); } //This creates the label var radioLabel = document.createElement("label"); radioLabel.setAttribute('for', flId + "_" + name); radioLabel.textContent = name; var objDiv = document.createElement("div"); objDiv.setAttribute('class', "q-radio"); objDiv.appendChild(radioItem); objDiv.appendChild(radioLabel); // --- 关键修改1:初始化时隐藏未选中的Removed选项 --- if (flId != null && flId === 'reasonCode' && name != null && name === 'Removed') { console.log("radio::"+flId + "_" + name); // 只有当当前选中的值不是Removed时,才隐藏该选项容器 if (!(flValue != null && flValue != undefined && flValue != "" && flValue === value)) { objDiv.style.display = 'none'; // 如果你有预定义的CSS隐藏类(比如.hidden { display: none; }),可以换成: // objDiv.classList.add('hidden'); } } //Append all radio buttons to the main RadioDiv - radioQuestion radioQuestion.appendChild(objDiv); if (radioItem.value == flValue && flValue != null && flValue != undefined && flValue != "") { radioItem.setAttribute('checked', "checked"); } // --- 关键修改2:添加change事件监听,动态切换Removed选项的显示状态 --- if (flId === 'reasonCode') { radioItem.addEventListener('change', function() { // 找到Removed选项对应的容器 const removedOptionDiv = document.getElementById(`${flId}_Removed`).closest('.q-radio'); if (this.value === 'Removed') { // 选中Removed时显示它 removedOptionDiv.style.display = 'block'; // 如果用CSS类的话:removedOptionDiv.classList.remove('hidden'); } else { // 选中其他选项时隐藏Removed removedOptionDiv.style.display = 'none'; // 如果用CSS类的话:removedOptionDiv.classList.add('hidden'); } }); } } //end of For loop
代码说明
- 初始化隐藏:在生成Removed选项的容器后,判断当前选中的
flValue是否为Removed,如果不是,直接设置容器的display: none(或者添加隐藏类) - 动态切换:给所有属于
reasonCode组的单选按钮添加change事件,当用户切换选中项时,自动显示/隐藏Removed选项的容器——这样即使用户后期切换选项,也能符合需求
内容的提问来源于stack exchange,提问作者Harry
相关产品推荐
相关产品推荐

