当已经有两个复选框时,如何无法选中



我有三个复选框,如下所示:

viewof year_range = 
Inputs.checkbox(["2020", "2021", "2022"], {value: ["2020", "2021"], label: "Year Range"})

如何只获得两个输入?

例如,如果选择了两个值,则第三个复选框将无法选中,当我取消选中两个值中的一个时,其他复选框将可以选中。

那么如何在这里添加条件来禁用第三个呢?

您可以这样做
(有关解释,请参阅代码中的注释。(

const boxesContainer = document.getElementById("boxes-container"),
boxes = boxesContainer.getElementsByTagName("input");
let checkedCount = 0; // Tracks number of checked boxes
// Calls handleCheckboxes when user checks/unchecks a box
boxesContainer.addEventListener("change", handleCheckboxes);

function handleCheckboxes({target}){
// Prevents handling any irrelevant events
if(target.attributes["type"]?.value != "checkbox"){ return; }
// If a box just became checked, increments count, and if count
//   has now reached 2, disables the remaining unchecked box
if(target.checked){
if(++checkedCount == 2){
for(const box of boxes){
if(box.checked != true){
box.setAttribute("disabled", "");
}
}
}
}
// A box just became unchecked, so decrements count, and if count
//   has now been reduced to 1, enables all boxes
else if(--checkedCount == 1){
for(const box of boxes){
box.removeAttribute("disabled");
}
}
}
<div id="boxes-container">
<label><input type="checkbox" value="2020"/>2020</label>
<label><input type="checkbox" value="2021"/>2021</label>
<label><input type="checkbox" value="2022"/>2022</label>
</div>

最新更新