至少一个复选框必须在其中一个取消选择操作时保持选中状态

Posted

技术标签:

【中文标题】至少一个复选框必须在其中一个取消选择操作时保持选中状态【英文标题】:at least one checkbox must stay selected on deselect action of one of them 【发布时间】:2017-09-25 02:32:29 【问题描述】:

我在表单上有几个复选框,我想在取消选择每个复选框时验证它们。所以至少有一个复选框必须在取消选择事件上保持选中状态。

function validateCBox() 
var checkBoxes = document.getElementsByClassName('myCBox');
var isChecked = false;
    for (var i = 0; i < checkBoxes.length; i++) 
        if ( checkBoxes[i].checked ) 
            isChecked = true;
        ;
    ;
    if ( isChecked ) 
        alert( 'checked!' );
         else 
            alert( 'please check at least one checkbox!' );
           
<form>
  <input type = "checkbox" class='myCBox' value = "a">1
  <input type = "checkbox" class='myCBox' value = "b">2 
  <input type = "checkbox" class='myCBox' value = "c">3
  <input type = "checkbox" class='myCBox' value = "d">4
</form>
<input type = "button" value = "Edit and Report" onClick="validateCBox()">

【问题讨论】:

您不使用单选按钮是否有原因? 【参考方案1】:

在您的示例中,您需要注册一个 click EventListener 以在单击复选框时调用 validateCBox()

使用click EventListener 的原因是因为您可以使用event.preventDefault() 取消事件。

var checkBoxes = document.getElementsByClassName('myCBox');

for (var i = 0; i < checkBoxes.length; i++) 
    checkBoxes[i].addEventListener('click', function(event) 
        validateCBox(event);
    );


function validateCBox(event) 
    var isChecked = false;
        
    for (var i = 0; i < checkBoxes.length; i++) 
        if (checkBoxes[i].checked) 
            isChecked = true;
        
    
    
    if (isChecked) 
        alert('checked!');
     else 
        alert('please check at least one checkbox!');
        event.preventDefault();
       
<form>
  <input type = "checkbox" class='myCBox' value = "a">1
  <input type = "checkbox" class='myCBox' value = "b">2 
  <input type = "checkbox" class='myCBox' value = "c">3
  <input type = "checkbox" class='myCBox' value = "d">4
</form>
<input type = "button" value = "Edit and Report" onClick="validateCBox()">

【讨论】:

谢谢托比。那么,是否可以在错误过程结束时选择最后一个?我的意思是警告后 @radeveloper 更新了答案,这是你的意思吗?阻止他们取消选中? 是的。谢谢托比。

以上是关于至少一个复选框必须在其中一个取消选择操作时保持选中状态的主要内容,如果未能解决你的问题,请参考以下文章