user2654953
user2654953

Reputation: 221

JS: looping function through checkbox array not counting properly

I want to validate the input on a series of checkboxes. There must be at least one checkbox selected, otherwise the user gets an alert to select one. However, the alert appears unless all of the checkboxes are selected.

I realize that the issue is how my for loop params are set, but I cannot figure out how to fix it.

for(var i=0;i<7;i++){
    if( !checkboxes[i].checked ){
        alert( 'You need to select at least one day!');
        checkboxes[i].focus();
        return false;
    }
}

Upvotes: 1

Views: 85

Answers (3)

Siamak Ferdos
Siamak Ferdos

Reputation: 3299

    var clicked = false;
    $(".CheckBoxClass").each(function () {            
        if($(this).checked ) clicked = true;
     }
     if(clicked)
        return true;
     else ...

Upvotes: 1

PhilVarg
PhilVarg

Reputation: 4820

You want to do the opposite of what you're coding. your current code flashes the alert if the current checkbox is not checked, that is, if ANY checkbox is not checked. you can modify it to something like this:

var isChecked = false;
for(var i=0;i<7;i++){
    if( checkboxes[i].checked ){
      isChecked = true;
    }
}

if ( !isChecked ) {
    alert( 'You need to select at least one day!');
    checkboxes[0].focus();
    return false;
}

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388326

You can use a flag to set the validation status and set it to true if atleast 1 item is checked.

Then after the loop check whether the flag is set else there are no checkboxes selected.

var valid = false;
for (var i = 0; i < checkboxes.length; i++) {
    if (checkboxes[i].checked) {
        valid = true;
        break;
    }
}

if (!valid) {
    alert('You need to select at least one day!');
    checkboxes[0].focus();
    return false;
}

Upvotes: 3

Related Questions