取消选择其中一个的操作时,必须至少选中一个复选框

时间:2017-04-27 10:37:28

标签: jquery validation checkbox

我在表单上有几个复选框,我想在取消选择每个表单时验证它们。因此,取消选择事件时,必须至少选中一个复选框。

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 个答案:

答案 0 :(得分: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()">