开发者

JQuery to determine if all checkboxlists (in div) have been checked

I am trying to use jQuery to do some validation 开发者_C百科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


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


function hasBoxesChecked(id) {
  return $(":checkbox:checked", document.getElementById(id)).length > 0;
}

Here's a live demo


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜