开发者

Add a check if any checkboxes are selected already w/jQuery

I have the following functions that add/remove a style to a button based on whether checkboxes on page are selected:

var checkboxes = $(".chkbx").change(function() {
    var allIsChecked = checkboxes.length === checkboxes.filter(":checked").length;
    all[0].checked = allIsChecked;
    enableMyElement(checkboxes.filter(":checked").length > 0);
});

var all = $("#checkall").change(function() {
    checkboxes.attr("checked",this.checked);
    enableMyElement(this.checked);
});

function enableMyElement(b) {
    $("#delBtn")[b?"removeClass":"addClass"]("dis");
}

Now, all this works fine but only on change. I need to add a check whether at least one of the checkboxes with class chkBx is checked on page load. I was thinking of adding another function, something like this

function CheckForAnySelected() {
    $(".chkbx").attr("checked").each( 
        function() {
            // do something
        }
    );

...but it does not look like a go开发者_Go百科od solution... and I am certainly not sure how to integrate with my existing code.


    function CheckForAnySelected() {    
        if($(".chkbx").filter(":checked").size()>0)
        {
          return true; // atleast one is selected
        }
       else{
      return false;
       });

you can use it like

if(CheckForAnySelected())
{
//atleast one is checked
}
else
{
// none checked
}

here is the fiddle http://jsfiddle.net/QNrZu/13/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜