views:

48

answers:

4

I am trying to use jQuery to do some validation on a form; I need a method where I can validate if all controls in a have been filled out \ selected. The CheckBoxLists my application supports are giving me a hard time as it seems like jQuery likes to address each checkboxes individually, but what I really need to do is evaluate all CBLs in a div and know if each has had at least one individual box checked.

I can name the DIV and the individual CBL's IDs as I see fit (so can do CBL1, CBL2, etc.). I really need a way to parse everything in a

A: 

You need to have at least 1 checkbox in each list selected. Wonder if this would work (make all the CBL's have an ID that starts with 'CBL' (eg. CBL1, CBL2,...)):

var valid = true;
$('[id^="CBL"]').each(function(i,v){
    valid = valid && ($(this).find(':checkbox:checked').size() >= 1);
});
alert(valid);

JSFiddle

Rocket
This checks if all checkboxes have been checked, not all checkbox *lists*.
Nick Craver
What's a checkbox list?
Rocket
@Rocket - It's a control in ASP.Net, rendered as a table or flow layout of checkboxes
Nick Craver
A checkbox list contains checkboxes, right? So, why wouldn't this work?
Rocket
@Rocket - You're requiring *every* checkbox in *every* list to be checked, not at least one in each.
Nick Craver
@Nick- Oh. Thanks. Ignore this answer then.
Rocket
How about this new edit?
Rocket
A: 
function hasBoxesChecked(id) {
  return $(":checkbox:checked", document.getElementById(id)).length > 0;
}

Here's a live demo

Josh Stodola
Note: demo uses actual output from two ASP.NET CheckBoxList controls
Josh Stodola
+2  A: 

Assuming that ASP parses your CBL as such:

<h2>Interests</h2>
<ul id='CBL1' class='checkboxlist'>
    <li><input type='checkbox' name='interest' value='javascript'> JavaScript</li>
    <li><input type='checkbox' name='interest' value='jquery'> jQuery</li>
</ul>
<h2>Hobbies</h2>
<ul id='CBL2' class='checkboxlist'>
    <!-- subsequent data -->

You could check this doing something like:

function validateCBLs() {
    var $lists = $('ul.checkboxlist');
    $lists.each(function(i, item) {
        if ($(item).find(':checked').length < 1) {
            //Show user an error, etc
            alert('Please, check at least one item from ' + $(item).attr('id'));
        }
    });
}

JSFiddle: Here

clarkf
+1 but... Why the $ signs in front of the variable name? Oh, and you need a var statement in there.
Billy ONeal
@Billy ONeal, some people prefix jQuery selector variables with `$` to identify it as a jQuery selector. I don't always, and I couldn't tell you why I did it here... Fixed the var statement.
clarkf
A: 

Try this:

$('.checkboxlist').filter(function(){
            return $(this).find(':checked').size()>0;
        }).size()

This will give you the number of CBLs that has at least one checkbox selected.

code90