How to get the values of selected checkboxes in a group using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery :checked Selector with each() method

The jQuery :checked selector can be used in conjugation with the each() method to retrieve the values of all checkboxes selected in group. The each() method used here simply iterates over all the checkboxes that are checked.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Get Values of Selected Checboxes</title>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
  • <script type="text/javascript">
  •     $(document).ready(function() {
  •         $("button").click(function(){
  •             var favorite = [];
  •             $.each($("input[name='sport']:checked"), function(){            
  •                 favorite.push($(this).val());
  •             });
  •             alert("My favourite sports are: " + favorite.join(", "));
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <form>
  •         <h3>Select your favorite sports:</h3>
  •         <label><input type="checkbox" value="football" name="sport"> Football</label>
  •         <label><input type="checkbox" value="baseball" name="sport"> Baseball</label>
  •         <label><input type="checkbox" value="cricket" name="sport"> Cricket</label>
  •         <label><input type="checkbox" value="boxing" name="sport"> Boxing</label>
  •         <label><input type="checkbox" value="racing" name="sport"> Racing</label>
  •         <label><input type="checkbox" value="swimming" name="sport"> Swimming</label>
  •         <br>
  •         <button type="button">Get Values</button>
  •     </form>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.