Blog Archive

jQuery Checkbox processing Example

To select a checkbox in jQuery you have to use the selector $(':checkbox') or $('[type=checkbox]'). Because :checkbox is a jQuery extension and not part of the CSS specification, queries using :checkbox will be slower than [type="checkbox"] in modern browsers.

In this example we will learn the following
  • Find all Selected Checkboxes and their Values
  • Reset all Selected Checkboxes
  • Dynamically select a Checkbox by Relative Index Number
  • Dynamically select a Checkbox by the Value
jQuery Checkbox processing Example
jQuery Checkbox Check all Selections

Source Code

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="robots" content="noindex,nofollow" />
<title>jQuery Checkbox Example</title>
<link rel="stylesheet" href="/resources/themes/master.css" type="text/css" />
 DIV {
  margin-bottom: 10px;
 rel="stylesheet" type="text/css" />
<script src="/resources/scripts/mysamplecode.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {

  var $mySelection = $("input[name='myFruit'][type='checkbox']:checked");
  if($mySelection.length > 0){
   var $message = "You have selected\n";
   $mySelection.each(function() {
    $message += $(this).val() + "\n";
  else {
   alert("Looks like you hate eating fruits"); 
  //same result you can choose to use either one
  $("input[name='myFruit']:checkbox")[1].checked = true;
  var $checkboxes = $("input[name='myFruit']:checkbox");
  var $checkboxes = $("input[name='myFruit']:checkbox");
  $checkboxes.each(function() {
   if($(this).val() === "Mango"){
    return false;
 <div id="allContent">
  <div id="myContent">
   <form id="samplecode" name="samplecode" method="POST" action="">
      <legend><b>&nbsp;&nbsp;&nbsp;Checkbox Selection&nbsp;&nbsp;&nbsp;</b></legend>
        <b>Select fruits that you like ...</b>
       <input type="checkbox" name="myFruit" value="Orange" /> Orange
       <input type="checkbox" name="myFruit" value="Apple" /> Apple
       <input type="checkbox" name="myFruit" value="Banana" /> Banana
       <input type="checkbox" name="myFruit" value="Mango" /> Mango
       <input type="checkbox" name="myFruit" value="Strawberry" /> Strawberry
       <input type="checkbox" name="myFruit" value="Other" /> Other
       <input id="checkNow" type="button" value="Click here to Check" />
       <input id="byIndex" type="button" value="Select Apple by Index" />
       <input id="reset" type="button" value="Reset any Selection" />
       <input id="byValue" type="button" value="Select Mango by Value" />