Select/Unselect checkbox(es) with Class Changer (Highlighter)

Posted on December 28, 2008, under JavaScript,  Bookmark it

js-class-changer

This is a tutorial that will give you an idea of how you can select/unselect all checkboxes from a form using JavaScript and also change the class style for the selected row from a table.

First, let’s create the HTML file containing the form and the table with its contents:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title>JavaScript Change Class</title>

  <meta name="Author" Content="Bit Repository">

  <meta name="Keywords" Content="change, class">
  <meta name="Description" Content="Change Class">

  <link rel="stylesheet" type="text/css" href="style.css" />

<script type="text/javascript" src="functions.js"></script>
</head>

<body>

<div style="width: 900px; text-align: left;" align="center">

<form id="form" name="form">
<table cellspacing="1">

<tr>
<td>&nbsp;</td>

<td>&nbsp;<strong>Title</strong></td>
<td>&nbsp;<strong>Description</strong></td>
</tr>

<tr id="tr1" class="one">
<td><input onClick="JavaScript: highlight('tr1', 'one', this.id);" type="checkbox" id="cb1" name="id[]" value="1"></td>

<td>&nbsp;<label for="cb1">Cras tempor faucibus nunc.</label></td>
<td>&nbsp;Lorem ipsum dolor sit amet, consectetur adipiscing elit.</td>
</tr>

<tr id="tr2" class="two">

<td><input onClick="JavaScript: highlight('tr2', 'two', this.id);" type="checkbox" id="cb2" name="id[]" value="2"></td>

<td>&nbsp;<label for="cb2">Quisque in nunc.</label></td>
<td>&nbsp;Etiam sit amet nibh. Integer sodales lacus ac ligula. </td>
</tr>

<tr id="tr3" class="one">

<td><input onClick="JavaScript: highlight('tr3', 'one', this.id);" type="checkbox" id="cb3" name="id[]" value="3"></td>

<td>&nbsp;<label for="cb3">Aenean commodo tincidunt odio</label></td>
<td>&nbsp;Sed euismod dignissim pede. Aliquam faucibus aliquam urna.</td>
</tr>

<tr id="tr4" class="two">

<td><input onClick="JavaScript: highlight('tr4', 'two', this.id);" type="checkbox" id="cb4" name="id[]" value="4"></td>

<td>&nbsp;<label for="cb4">Cras semper pulvinar quam.</label></td>
<td>&nbsp;Mauris vehicula turpis ac nisl. Nulla facilisi. Maecenas eget enim quis nunc varius sodales. </td>
</tr>

<tr id="tr5" class="one">

<td><input onClick="JavaScript: highlight('tr5', 'one', this.id);"  type="checkbox" id="cb5" name="id[]" value="5"></td>

<td>&nbsp;<label for="cb5">Pellentesque in urna.</label></td>
<td>&nbsp;Nam dapibus aliquam tortor. Donec at mi pharetra arcu luctus rutrum. </td>
</tr>

<tr id="tr6" class="two">

<td><input onClick="JavaScript: highlight('tr6', 'two', this.id);" type="checkbox" id="cb6" name="id[]" value="6"></td>

<td>&nbsp;<label for="cb6">Pellentesque vehicula rutrum lectus.</label></td>
<td>&nbsp;Nunc imperdiet tempus erat. Phasellus lacus nisl, molestie blandit, semper a, dictum at, nulla.</td>
</tr>

</table>

</form>

<a href="JavaScript: check_all();">Check</a> / <a href="JavaScript: uncheck_all();">Uncheck</a> All</a>

</div>
 </body>
</html>

In the TABLE there are alternating row colors. Class ‘one’ is with a white background, while class ‘two’ with a soft green background. Both the TR and INPUT (checkbox) elements have unique ID which are used by the JS functions in order to highlight a specific row and also remove the highlight and restore the initial class assigned to that particular row. Inside each checkbox input there is the ‘onClick’ attribute which triggers highlight() from the functions.js. Three arguments are passed: the id of the TR element, the current class of TR and the ID of the checkbox.

Let’s analyze the highlight() function:

/* Highlight Row */
function highlight(id, currentClass, checkboxId)
{
   var checkbox_element = document.getElementById(checkboxId);
   var row_element = document.getElementById(id);

   row_element.className = checkbox_element.checked ? 'selected' : currentClass;
}

id – table row unique id
currentClass – the current class of that row (TR)
checkboxId – the unique id of the checkbox input element

The HTML DOM getElementById() Method returns a reference to the first object with the specified ID (each element should have its unique ID). After we set references for both the TR and INPUT element we now have to use the ‘className‘ property to return the class attribute of the element. If the user clicks on the INPUT checkbox, the class ‘selected’ is assigned to TR and the row will be filled with a soft blue background. Otherwise, the original class would be restored to the TR (this is the case when the user removes the checkmark).

Now let’s move to the check_all() function which checks & highlights (calling highlight_all() ) all the (checkbox) inputs:

/* Check All */

function check_all()
{
var num_checkboxes = document.forms[0].elements.length;

   for(i = 0; i < num_checkboxes; i++)
   {
      if(document.forms[0].elements[i].type == 'checkbox')
      {
         document.forms[0].elements[i].checked = true;
      }
   }
   highlight_all(num_checkboxes);
}

First, we need to determine the number of checkboxes from the form. To do that we will use:

var num_checkboxes = document.forms[0].elements.length;

Now, we will use for to loop through each checkbox and mark it:

for(i = 0; i < num_checkboxes; i++)
   {
      if(document.forms[0].elements[i].type == 'checkbox')
      {
         document.forms[0].elements[i].checked = true;
      }
   }

Lastly, we need to highlight all marked checkboxes by calling highlight_all(), passing the 'num_checkboxes' to it.

/* Highlight All Rows (this happens when 'check_all' is triggered */

function highlight_all(num)
{
   for(i = 1; i < = num; i++)
   {
      document.getElementById('tr' + i).className = 'selected';
   }
}

The for() function is used to go through each row (the number of rows are equal to the number of checkboxes) and apply the 'selected' class to it.

The uncheck_all() function is used to remove all the marks from the checkboxes and restore the original class for each row by calling remove_highlight_for_all () (from 'selected' to either 'one' or 'two'):

/* Uncheck All */

function uncheck_all()
{
var num_checkboxes = document.forms[0].elements.length;

   for(i = 0; i < num_checkboxes; i++)
   {
      if(document.forms[0].elements[i].type == 'checkbox')
      {
         document.forms[0].elements[i].checked = false;
      }
   }
   remove_highlight_for_all(num_checkboxes);
}

It is quite similar to check_all(). Using for, we remove the mark for each checkbox. The remove_highlight_for_all() function is used to remove the 'selected' class from all rows and restore their original look (with color alternation):

/* Remove highlight for all Rows (this happens when 'uncheck_all' is triggered */

function remove_highlight_for_all(num)
{
   for(i = 1; i < = num; i++)
   {
      var initial_class = (i % 2) ? 'one' : 'two';
      document.getElementById('tr' + i).className = initial_class;
   }
}

Here's the complete functions.js file with all the necessary functions:

/* Highlight Row */
function highlight(id, currentClass, checkboxId)
{
   var checkbox_element = document.getElementById(checkboxId);
   var row_element = document.getElementById(id);

   row_element.className = checkbox_element.checked ? 'selected' : currentClass;
}

/* Check All */

function check_all()
{
var num_checkboxes = document.forms[0].elements.length;

   for(i = 0; i < num_checkboxes; i++)
   {
      if(document.forms[0].elements[i].type == 'checkbox')
      {
         document.forms[0].elements[i].checked = true;

      }
   }
   highlight_all(num_checkboxes);
}

/* Uncheck All */

function uncheck_all()
{
var num_checkboxes = document.forms[0].elements.length;

   for(i = 0; i < num_checkboxes; i++)
   {
      if(document.forms[0].elements[i].type == 'checkbox')
      {
         document.forms[0].elements[i].checked = false;
      }
   }
   remove_highlight_for_all(num_checkboxes);
}

/* Highlight All Rows (this happens when 'check_all' is triggered */

function highlight_all(num)
{
   for(i = 1; i <= num; i++)
   {
      document.getElementById('tr' + i).className = 'selected';
   }
}

/* Remove highlight for all Rows (this happens when 'uncheck_all' is triggered */

function remove_highlight_for_all(num)
{
   for(i = 1; i <= num; i++)
   {
      var initial_class = (i % 2) ? 'one' : 'two';
      document.getElementById('tr' + i).className = initial_class;
   }
}

This is the content of style.css. You can make any changes you wish such as changing the colors for the classes:

HTML, BODY { padding: 0; border: 0px none; }

TABLE { border: 1px solid #cdcdcd; }

FORM { margin: 0px; }

.one { background-color: white; }
.two { background-color: #E6F9E6; }
.selected { background-color: #E0EFF7; } 

Happy coding ;-)

Share the Love
Get Free Updates

Comment via Facebook

One Reply to "Select/Unselect checkbox(es) with Class Changer (Highlighter)"

  1. i can’t seem to get it working with dynamic id’s… all looks fine – the results are each in individual tables & divs… could that be the problem?

    Dan

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)