HOW TO FIND HOW MANY CHECKBOX ARE CLICKED IN JQUERY

Sometimes there is need to find how many checkbox is clicked. For e.g  we have many checkbox of teeth number and there we want to show how many checkbox 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 input selector of JQuery.
  2. Find how many checkbox is checked by using  :checked attribute of JQuery.
  3. Find the length of checked input by using .length attribute.
  4. Show in div or whatever place wherever you want to show.

Leave a Comment