Wednesday 13 June 2012

Examples of Using jQuery with JSF and Richfaces

I had difficulty finding examples of using jQuery with JSF and RichFaces so I have listed a couple of examples below.  My environment was Websphere 6.1, JSF 1.2, and Richfaces 3.3

Example 1
Add an onclick listener to all links.  Adapted from How jQuery Works:

<ui:define name="extraHeaderContent">
   <a4j:loadScript src="resource://jquery.js" />


<script language="javascript">
// use CDATA to prevent greater than in if statements being 
// interpreted as the start of a tag
//<![CDATA[
// ask jQuery to do what follows after the page is loaded
   jQuery(document).ready(function(){
   // find all links (a) and set a click handler
jQuery("a").click(function(event){
    alert("Thanks for visiting!");
    // do not go to the link
    event.preventDefault();
  }); 
});
//]]>
</script>
</ui:define>

Example 2
Allow users to paste from Excel into a series of JSF inputText fields.  The example will only work when using Microsoft Internet Explorer browser due to the use of window.clipboardData.  It is possible to make the below usable on other browsers but that was not one of my requirements.  It pastes a series of up to 12 numbers copied from Excel:


<ui:define name="extraHeaderContent">
    <a4j:loadScript src="resource://jquery.js" />
    
<script language="javascript">
//<![CDATA[
// wait until document is loaded before trying to find DOM elements
jQuery(document).ready(function() {
for (var i=0; i<12; i++) {
bindField(i);
}
});


function bindField(inputFieldNum) {
jQuery("#form\\:adjId"+inputFieldNum).bind('paste', function() {
var el = $(this);
       setTimeout(function() {
           clip(inputFieldNum);
       }, 0);
});
}


function clip(firstInputFieldNum) {
//http://stackoverflow.com/questions/1095131/paste-excel-data-into-html-table

   // get the clipboard text
   var clipText = window.clipboardData.getData('Text');


   // split into cells
   //Excel separates columns with tabs (chr(9)), rows with CR (chr(13)), but cater for various splitter chars
   var clipCells = clipText.split(/[\r\n\t,]/);
   var numCells = clipCells.length;


   if (numCells<=(12-firstInputFieldNum)) {
   // overwrite each month's adjustment figure with the clipCells
   for (var i=0; i<numCells; i++) {
   var elementName = 'form:adjId'+(firstInputFieldNum+i);
   document.getElementById(elementName).value = clipCells[i];
   }
} else {
alert('Too many cells');
}
}
//]]>
</script>
</ui:define>

1 comment:

  1. Therefore, if you want to be successful, you need to feel more gratitude. Fortunately, gratitude, like most emotions, is like a muscle: The more you use it, the stronger and more resilient it becomes.
    evening party saree

    ReplyDelete