mercredi 16 août 2017

Checkbox validation for checking at least 1 checkbox and at most 3 using javascript

At least one checkbox should be checked and at max 3 checkboxes can be checked.

function checkout(){
    var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
    if (checkBoxes.length > 3){
        alert('You cannot select more than 3 books');
        return false;
    }
    if (checkBoxes.length == 0) {
        alert('Please select at least 1 book');
        return false;
    }

But with this code, irrespective of the number of books I am selecting, the message 'You cannot select more than 3 books is appearing'.

For satisfying the just one checkbox needs to be checked, I used the following code, which worked fine.

function checkout(){
    var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
    var isChecked = false;
    for (var i = 0; i < checkBoxes.length; i++) {
        if ( checkBoxes[i].checked ) {
            isChecked = true;
        };
    };
    if ( isChecked ) {
        alert( 'Your books have been sent to your mail !' );
    } else {
       alert( 'Please, check at least one checkbox!' );
       return false;
    }
}

But how do I get the maximum constraint in?

Any help would be greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire