24
Dec
09

Managing JSF Checkboxes


This page describes the process of using checkboxes in your JSF enabled application to select all, select one or select multiple records in a dataTable.

In the examples below JavaScript is required. Submitting an http request to get the component state updated is not acceptable for a good user experience.

JSF Datatable

The following JSF code uses javascript defined below to check and un-check boxes.

<t:datatable renderedifempty="false" cellpadding="2" cellspacing="1" columnclasses="leftAlignCol" headerclass="list-header" id="dataTable1" rowclasses="list-row-even,list-row-odd" styleclass="dataTable" value="#{myBackingBean.queryResult}" var="currentRow" width="100%">
   <h:column>
       <t:selectbooleancheckbox forceid="true" id="chk" onclick="onChangeSelect(this);" value="#{myBackingBean.selected}"></t:selectbooleancheckbox>
       <f:facet name="header">
           <h:outputtext value="Selected"></h:outputtext>
       </f:facet>
  </h:column>
      :
    more columns
      :
</t:datatable>

JQuery

Using JQuery makes working with javascript easier. For example to implement the select all feature all you need to do is the following.

To get jquery just download it from their homepage. It is a small js file. Put it in the same directory as your html. Include this in the header of the page.

      <script src="jquery-1.3.2.min.js" type="text/javascript"></script>

include the following code that checks and unchecks the checkboxes.

   <a href="#" onclick="$('form :checkbox').attr('checked', 'checked');">Select All</a> 
   <a href="#" onclick="$('form :checkbox').attr('checked', '');">Un-Select All</a>

Thats all there is to it!

Doing it the OLD School way

If you guys insist in doing it the old way please read on. However take note that when you use pagination the second page will not work. The will only work when all the results are displayed on one page.

The old school method will only work if you use the tomahawk tag library and specify (forceId=”true” id=”chk” ). This allows us to write javascript that can check / uncheck the boxes referencing them via id. Otherwise JSF would have generated all sort of random id’s that would be difficult. JQuery does not have this problem since we are using the selector functionality. Even if the id’s were random JQuery would be able to check/uncheck the boxes.

Javascript Functions

To get all of this done we need the following javascript functions.

  1. Generic Function to get an element by its’ id.
  2. Generic function to  check to see if any item in the array has been checked
  3. Generic Function to call function 2 and enable a command button if it returns true
  4. Generic function to  hide or show an object using CSS.
  5. Select All Javascript

1. Gets an object based on its element id.

function getObj(objId, formId) {
        var fullId = objId;
        if (formId != null &amp;&amp; formId.length &gt; 0) {
            fullId = formId + ':' + objId;
        }
        //alert('getting object: ' + fullId);
        var elem = null;
        if (document.getElementById) {
            elem = document.getElementById(fullId);
        } else if (document.all) {
            elem = document.all[fullId];
        } else if (document.layers) {
            elem = document.layers[fullId];
        }
        return elem;
}

2. Generic function to check to see if any item in the array has been checked

/*
 * Browser-safe. Checks to see if an array of check boxes has any which are
 * checked. Boxes have ids like check[0], check[1], ... , check[n] where 'check'
 * is the base Id that has been assigned to the group.
 *
 * Param:               arrayId - String - id of element group to change
 * Returns:             boolean (true one or more checked) false (else)
 */
function checkBoxArrayHasChecked(arrayId) {
    for (i = 0; ; i++) {
        id = arrayId + '[' + i + ']';
        elem = getObj(id);
        if (elem == null) {
            break;
        } else if (elem.checked) {
           return true;
        }
    }
    return false;
}

3. Generic Function to call function 2 and enable a command button if it returns true

Custom function that will enable a component if at least one checkbox is checked.

var cmdBtnId = 'cmdbtn';
var formId = 'frm1';
var checkBoxArrayId = 'chk';
function onChangeSelect(checkbox) {
    // Render the transfer button if one or more checkboxes are selected
    hideOrShowObject(formId, cmdBtnId, checkBoxArrayHasChecked(checkBoxArrayId));
}

4. Generic function to check or un-check all elements in an array

/*
 * Browser-safe. Check or uncheck an array of checkboxes. Boxes have ids
 * like check[0], check[1], ... , check[n] where 'check' is the base Id that
 * has been assigned to the group.
 *
 * Param:               arrayId - String - id of element group to change
 * Param:               state - boolean - true (check all elements) false (uncheck all elements)
 * Returns:             nothing
 */
function checkBoxArraySet(arrayId, state) {
    for (i = 0; ; i++) {
        id = arrayId + '[' + i + ']';
        elem = getObj(id);
        if (elem == null) {
            break;
        } else {
            elem.checked = state;
        }
    }
}

5. Select All Javascript

The next javascript is implementation specific that will run when user clicks (select or un-select) all.

function setAll(state) {
    // Set the checkBox array on or off
    checkBoxArraySet(checkBoxArrayId, state);
}

Example

An example of a component that calls the above function.

<h:graphicimage onclick="setAll(true);" id="all" url="resources/add.gif" title="Select all records..."></h:graphicimage>

Another Example

		<a href="#" onclick="setAll(true);">
		     <h:outputtext value="Select all"></h:outputtext>
		</a><br>
		<a href="#" onclick="setAll(false);">
		     <h:outputtext value="de-Select all"></h:outputtext>
		</a>
About these ads

0 Responses to “Managing JSF Checkboxes”



  1. Leave a Comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 58 other followers

December 2009
S M T W T F S
« Nov   Jan »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Blog Stats

  • 567,319 hits

Follow

Get every new post delivered to your Inbox.

Join 58 other followers

%d bloggers like this: