1

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;
    }
}
1
  • 1
    Basically, what you're doing is looping through all the checkboxes, and immediately doing alert('You need to select at least one day!'); the moment any of the checkboxes are not checked. Commented Jun 1, 2015 at 3:49

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Arun. Worked like a charm! I guess as I get more experience with the language I will be able to better understand how to figure out these types of challenges.
1

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;
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.