Search code examples
jqueryformscountjquery-selectors

jQuery count checked checkbox in next element


My sample is counting every single checkbox on a page. How to count the checked checkboxes on next/sibling element with jQuery?

PS: I want this to work on multiple forms on a single page without calling the element(form) ID.

$(document).ready(function() {
  function countChecked() {
    var tCount = $("input:checked").length;
      $(".totalchecked").text( tCount + ' selected');
  }
  countChecked();
  var tCheck = $(".totalchecked");
  $(tCheck).next().find(":checkbox").click(countChecked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>form 1:
  <div class="totalchecked">0 selected</div>
  <div>
    <input type="checkbox" class="class" name="1">
    <input type="checkbox" class="class" name="2">
    <input type="checkbox" class="class" name="3">
  </div>
</div>
<div>form 2:
  <div class="totalchecked">0 selected</div>
  <div>
    <input type="checkbox" class="class" name="4">
    <input type="checkbox" class="class" name="5">
    <input type="checkbox" class="class" name="6">
  </div>
</div>

/* Update */
I want something like this.
enter image description here


Solution

  • Check this working sample:

    function checkTotalCheckedBoxes(){
    $("div" ).each(function( ) {
      if(this.children.length === 3){ 
      var checked = 0;
    	$(this.children).each(function() {
            this.checked ? checked++ : null;      
            $("input[name="+this.name+"]").parent().siblings().closest('.totalchecked')[0].innerText = (checked) + " selected"; 
    
      	    });
      }
    });
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>form 1:
      <div class="totalchecked">0 selected</div>
      <div>
    <input type="checkbox" class="class" name="1"  onclick="checkTotalCheckedBoxes()">
    <input type="checkbox" class="class" name="2"  onclick="checkTotalCheckedBoxes()">
    <input type="checkbox" class="class" name="3"  onclick="checkTotalCheckedBoxes()">
      </div>
    </div>
    <div>form 2:
      <div class="totalchecked">0 selected</div>
      <div>
    <input type="checkbox" class="class" name="4"  onclick="checkTotalCheckedBoxes()">
    <input type="checkbox" class="class" name="5"  onclick="checkTotalCheckedBoxes()">
    <input type="checkbox" class="class" name="6"  onclick="checkTotalCheckedBoxes()">
      </div>
    </div>