HOW TO FIND HOW MANY CHECKBOX ARE CLICKED IN JQUERY

HOW TO FIND HOW MANY CHECKBOX ARE CLICKED IN JQUERY

 

Sometimes there is a need to find how many checkboxes are clicked. For e.g, we have many checkboxes of teeth number and there we want to show how many checkboxes of teeth number is clicked. So the solution is using length attribute of JQuery.

count-checkbox-clicked

Complete Code

<!DOCTYPE html>

<html>

<head>

<meta HTTP-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Untitled Document</title>

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<style>

  div {

    color: red;

  }

  </style>

</head>
<body>

<input type="checkbox" value="cricket"   class="hobbies ">Cricket <br>

<input type="checkbox" value="hockey"   class="hobbies ">Hockey

<div></div>
<script>

var countChecked = function() {

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

  $( "div" ).text(n);

};

countChecked();
$( ".hobbies " ).on( "click", countChecked );

</script>
</body>
</html>

Here the logic is that :

  1. Select the checkbox input by using the input selector of JQuery.
  2. Find how many checkboxes are checked by using: checked attribute of JQuery.
  3. Find the length of checked input by using the .length attribute.
  4. Show in div or whatever place wherever you want to show.