jeudi 27 avril 2017

at least one checkbox must stay selected on deselect action of one of them

I have a few checkboxes on a form and i want to validate them when deselecting every one of them. So at least one checkbox must stay selected on deselect event.

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()">



Aucun commentaire:

Enregistrer un commentaire