最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I check if any checkboxes at all on the page are checked? - Stack Overflow

programmeradmin2浏览0评论

I need to check, using jQuery, if any checkboxes on the page are checked. The particular checkbox set they are contained in doesn't matter, just any of them.

Any ideas?

Thanks!

I need to check, using jQuery, if any checkboxes on the page are checked. The particular checkbox set they are contained in doesn't matter, just any of them.

Any ideas?

Thanks!

Share Improve this question asked Feb 2, 2012 at 20:22 samilessamiles 3,90014 gold badges51 silver badges76 bronze badges
Add a comment  | 

7 Answers 7

Reset to default 10

var isChecked = $("input[type=checkbox]").is(":checked");

or

var isChecked = $('input:checkbox').is(':checked')

The following function returns true if there are any ticked checkboxes and false otherwise.

function anyCheckbox()
{
    var inputElements = document.getElementsByTagName("input");
    for (var i = 0; i < inputElements.length; i++)
        if (inputElements[i].type == "checkbox")
            if (inputElements[i].checked)
                return true;
    return false;
}
if($('checkbox:checked').length > 0)
    //Some checkbox is checked

This should find any checkboxes on the page that are checked

if you only want to look at checkboxes, not radio buttons: var isChecked = $("input:checkbox").is(":checked");

if you're ok with checkboxes or radio buttons: var isChecked = $("input").is(":checked");

This works:

var ischecked =$('input[type=checkbox]:checked').length;

so

if (ischecked > 0)

then at least one is checked.

function checkbox(){
    var ischecked =$('input[type=checkbox]:checked').length;
    if (ischecked <= 0){        // you can change your condition
    alert("No Record Selected");
    return false;
    }else
    {
      -------//your Action that you want
    }

}

Here is the modern JS way, without using jQuery:

Array.from(document.querySelectorAll('[type=checkbox]')).some(x => x.checked)

It will return true if at least one checkbox is checked, false otherwise.

发布评论

评论列表(0)

  1. 暂无评论