HOW TO GET VALUE OF MULTIPLE CHECKBOX CLICKED IN J QUERY AND SHOW IN DIV.

Sometimes student or professional have need to get value of multiple checkbox clicked and show in div. Here is the solution of that :  

Step 1 : Make two or more checkbox input

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

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

Step 2 : Assign class in checkbox input and give class name whatever you want, Here in this e.g  class name is hobbies.

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

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

Step 3 : Make div, paragraph or any place  where you want  to show the selected value of checkbox. Here we are using div to show the selected value of checkbox  

<div></div>

 

Step 4 : Use JQuery library in header or footer for running JQuery code.

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

 

Step 5 : Use JQuery script after using JQuery library, paste this code in footer before closing body tag.

<script type="text/javascript">

$(document).ready(function(){            

  $(".hobbies").click(function(){          

  var testval = [];

     $('.hobbies:checked').each(function() {

       testval.push($(this).val());

     });

  alert(testval);

 });

});

</script>

 

Here in this script the logic is that :

  1. We are selecting checkbox input by using class selector, Here class name is hobbies.
  2. Holding multiple value of checkbox into an array variable testval[].
  3. Checking checkbox is checked or not by using :checked attribute selector in JQuery and iterating or looping to get the value one by one by using each() function in jquery.
  4. After get all value of checkbox we are assigning into the div or whatever place wherever we want to show.

Complete Code is here :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<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>

</head>

<body>

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

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

<div></div>

<script type="text/javascript">

$(document).ready(function(){            

  $(".hobbies ").click(function(){          

  var testval = [];

     $('.hobbies:checked').each(function() {

       testval.push($(this).val());

     });

  $(“div”).text(testval);

 });

});

</script>

</body>

</html>

Leave a Comment