How do I count how many checkboxes are selected on a page with jQuery

前端 未结 4 1573
感动是毒
感动是毒 2021-01-01 18:28

I want to count how many checkboxes on my page are selected using jQuery. I\'ve written the following code:

      var numberOfCheckboxesSelected = 0;
               


        
相关标签:
4条回答
  • 2021-01-01 18:38

    The first argument passed to the callback in each is the index, not the element. You should use this or a second argument:

    $(':checkbox').each(function(idx, checkbox) {
          if (checkbox.attr('checked'))
              numberOfCheckboxesSelected++;
    });
    

    Moreover, the easier way to do this is to select only the checked elements with the :checked selector and then check the selection's length property:

    var numberOfCheckboxesSelected = $('input:checkbox:checked').length;
    
    0 讨论(0)
  • jQuery supports the :checked pseudo-selector.

    var n = $("input:checked").length;
    

    This will work for radio buttons as well as checkboxes. If you just want checkboxes, but also have radio buttons on the page:

    var n = $("input:checkbox:checked").length;
    
    0 讨论(0)
  • 2021-01-01 18:46

    Try this(to avoid counting any selected radio buttons):

    var numberOfCheckboxesSelected = $('input[type=checkbox]:checked').length; 
    
    0 讨论(0)
  • 2021-01-01 18:54
    $("input:checked").length
    

    this will return the count of checked checkboxes.

    0 讨论(0)
提交回复
热议问题