3.0.5

Code for retrieving On/Off status of checkboxes

Having seen a ton of posts regarding checkboxes, I decided to search for a good way to retreive the on/off status of checkboxes in the grid. After not finding much (without using a Checkbox Template), I decided to write one myself. :)

Assumptions:

1) The checkbox is in its own cell
2) You are not trying to retreive the value attribute of the checkbox, you just want to see if it is checked or not. Speaking of attributes, I did not use the form tag to get this to work.
3) I would recommend putting the checkbox in its own cell without any other text (such as a label), as the "onclick" event handler is looking for which cell has been clicked, thus assuming that the checkbox itself has been turned on or off, not just that the cell it's in has been clicked.

To start off, we'll need some data:
var myData = [
   ["<input type=checkbox>","MSFT","Microsoft Corporation", "314,571.156", "32,187.000", "55000"],
   ["<input type=checkbox>","ORCL", "Oracle Corporation", "62,615.266", "9,519.000", "40650"],
...
var myColumns = [
   "", "Ticker", "Company Name", "Market Cap.", "$ Sales", "Employees"


Now, let's set up an array where each element corresponds to a row:
// Array of what is and isn't checked
var isChecked = new Array();
for(var i=0;i<20;i++) {
   isChecked[i] = 0;
}

This assumes that we have 20 rows, of course. Alternately, I could've just done this, I reckon: :)
var isChecked = new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);


After creating the grid, we then capture an "onclick" event:
// Store array of what's been checked
// Note: works only for getting on/off status & not for getting a "value"
var isItChecked = function(src) {
   // If we don't set the selected item now, 
   // then it won't happen until *after* this function exits.
   var theIndex = src.getProperty("item/index");
   obj.setProperty("selection/index",theIndex);
   // Make sure we clicked the checkbox and 
   // not something else on the grid
   if(src.getProperty("item/text").indexOf("<input type=checkbox>") != -1) {
      (!(isChecked[theIndex])) ? isChecked[theIndex] = 1 : isChecked[theIndex] = 0;
    }
}
obj.setAction("click", isItChecked);


I then added a button on the interface to tell me which items have been checked. Please note that I have it set up to tell you which items have been checked in their original order, not the sorted order.
function seeChecked() {
   for(var i=0;i<isChecked.length;i++) {
      if(isChecked[i]) {
         alert("Item " + i);
      }
   }
}


Lastly, I added a button to the interface:
<P><input type=button value="See what's checked" onClick="javascript:seeChecked();">


Hope that everyone interested finds this useful. :)
Brian McCrary
July 12,

This topic is archived.

See also:


Back to support forum