Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Monday, December 8, 2014

Building dynamic responsive multi-level menus with plain HTML and OmniFaces

Recently, I had to create a responsive multi-level menu with JSF 2.2. Requirements: the menu should
  • be created with dynamic structure from backend
  • be responsive, i.e. desktop- and mobile-friendly
  • have submenu items with navigation links
  • support touch events
  • support keyboard accessibility
PrimeFaces' menus were not a choice. They can indeed be created programmatically by model, but
  • they are not really responsive
  • submenu items only collapse / expand the submenus and can not contain navigation links
  • ...
Well, why not to pick any jQuery based plugin for responsive multi-level menus? There are a lot of plugins. See Useful List of Responsive Navigation and Menu Patterns. I choosen FlexNav.

But how to output the dynamic menu structure? ui:repeat is not a choice here because the structure (nested sub menus, etc.) is not known a priori. Fortunately, there is OmniFaces with o:tree, which allows to have full control over the markup of a tree hierarchy by declaring the JSF components or HTML elements in the markup. o:tree does not render any HTML markup by itself. Exactly what I need!

I ended up with this XHTML fragment mixing o:treeNode, o:treeNodeItem, o:treeInsertChildren and HTML elements defined by the mentioned FlexNav menu:
<h:outputScript library="js" name="jquery.flexnav.js"/>
<h:outputStylesheet library="css" name="flexnav.css"/>

<ul id="mainnavi" class="flexnav" data-breakpoint="640" role="navigation">
    <o:tree value="#{mainNavigationBean.treeModel}" var="item">
        <o:treeNode level="0">
            <o:treeNodeItem>
                <li class="item">
                    <a href="#{item.href}" title="#{item.title}">#{item.text}</a>
                    <o:treeInsertChildren/>
                </li>
            </o:treeNodeItem>
        </o:treeNode>
        <o:treeNode>
            <ul>
                <o:treeNodeItem>
                    <li>
                        <a href="#{item.href}" title="#{item.title}">#{item.text}</a>
                        <o:treeInsertChildren/>
                    </li>
                </o:treeNodeItem>
            </ul>
        </o:treeNode>
    </o:tree>
</ul>

<h:outputScript id="mainnaviScript" target="body">
    $(document).ready(function () {
        $("#mainnavi").flexNav({'calcItemWidths': true});
    });
</h:outputScript>
The OmniFaces' TreeModel with menu items is created programmatically. The Java code looks like
public TreeModel<NavigationItemDTO> getTreeModel() {
    // get menu model from a remote service
    NavigationContainerDTO rootContainer = remoteService.fetchMainNavigation(...);

    TreeModel<NavigationItemDTO> treeModel = new ListTreeModel<>();
    buildTreeModel(treeModel, rootContainer.getNavItem());

    return treeModel;
}

private void buildTreeModel(TreeModel<NavigationItemDTO> treeModel, List<NavigationItemDTO> items) {
    for (NavigationItemDTO item : items) {
        buildTreeModel(treeModel.addChild(item), item.getNavItem());
    }
}
And the end result (desktop variant):


Note that submenus are clickable and can be expanded on mouseover.

You see, JSF is flexible and sometimes you don't need full-blown components. Have fun!

Monday, July 7, 2014

How to implement a custom password strength indicator in JSF

Verifying password strength using JavaScript is a common task. In this post, I will show how to add a password strength indicator to an JSF based web application. The password component in PrimeFaces already has a feedback indicator of the password strength, but it has two major shortcomings:
  • Feedback indicator is not responsive (fix width, not mobile friendly, etc.)
  • Rules for the password strength verification are hard coded in JavaScript. No customization is possible.
What we need is a good looking, easy customizable and responsive password strength indicator / meter. Fortunately, PrimeFaces has another component - progress bar which we can use for our purpose. This is not a misusage. The end result is actually impressive.

Let's start with XHTML. First, define a quite normal passwort field.
 
<p:password id="passwort" value="#{mybean.password}" label="Password" required="true" autocomplete="off"/>
 
Second, define a progress bar with displayOnly="true" and some messages for the passwort strength (weak, medium, strong).
<div style="white-space:nowrap;">
    <h:outputText value="Password strength "/>
    <h:outputText id="pwdWeak" value="weak" style="display:none" styleClass="bold weakMsg"/>
    <h:outputText id="pwdMedium" value="medium" style="display:none" styleClass="bold mediumMsg"/>
    <h:outputText id="pwdStrong" value="strong" style="display:none" styleClass="bold strongMsg"/>
</div>
<p:progressBar id="pwdStrength" value="0" styleClass="pwdStrength" displayOnly="true"/>
Let's go to the JavaScript part. We need a script block (placed somewhere after the p:progressBar) where we intend to invoke a custom JS function setupPasswordStrength().
<script type="text/javascript">
    $(document).ready(function () {
        setupPasswordStrength("passwort", "pwdStrength");
    });
</script>
The JS function has two arguments: an Id of the password field and an Id of the progress bar. In the function, we will register a callback for the namespaced keyup event. In the callback, we will check the current input value by means of reg. expressions. We would like to take the following rules (rules are up to you):
  • Password length is less than 8 characters or doesn't contain at least one digit ==> weak password
  • Password length is equal or greater than 8 characters, contains at least one digit, but doesn't have at least one lower and one upper case letter OR one special char: ==> medium password
  • Password length is equal or greater than 8 characters, contains at least one digit AND has at least one lower and one upper case letter OR one special char: ==> strong password
These are good rules I have often seen across the internet. Let's me show the JS function.
function setupPasswordStrength(pwdid, pbarid) {
    // reg. exp. for a weak password
    var weak = XRegExp("^(?=.*\\d{1,}).{8,}$");
    // reg. exp. for a strong password
    var strong = XRegExp("^(?=.*[a-z])(?=.*[A-Z]).+|(?=.*[!,%,&,@,#,$,^,*,?,_,~,\\-]).+$");

    var $this = $("#" + pwdid);
    var pbar = $("#" + pbarid).find(".ui-progressbar-value");

    // visualize on keyup
    $this.off('keyup.' + pwdid).on('keyup.' + pwdid, function(e) {
        visualizePasswordStrength($(this).val(), pbar, weak, strong);
    });

    // fix chrome issue with autofill fields
    setTimeout(function(){$this.triggerHandler('keyup.' + pwdid);}, 150);
}

function visualizePasswordStrength(pwd, pbar, weak, strong) {
    var pparent = pbar.parent().parent().parent();
    var weakMsg = pparent.find(".weakMsg");
    var mediumMsg = pparent.find(".mediumMsg");
    var strongMsg = pparent.find(".strongMsg");

    if (pwd == null || pwd.length < 1) {
        pbar.removeClass("weak medium strong");
        weakMsg.hide();
        mediumMsg.hide();
        strongMsg.hide();
        return;
    }

    if (!weak.test(pwd)) {
        // weak
        pbar.removeClass("medium strong").addClass("weak");
        mediumMsg.hide();
        strongMsg.hide();
        weakMsg.show();
        return;
    }

    if (!strong.test(pwd)) {
        // medium
        pbar.removeClass("weak strong").addClass("medium");
        weakMsg.hide();
        strongMsg.hide();
        mediumMsg.show();
        return;
    }

    // strong
    pbar.removeClass("weak medium").addClass("strong");
    weakMsg.hide();
    mediumMsg.hide();
    strongMsg.show();
}
In the function visualizePasswordStrength(), we remove and add style classes to the progress bar dependent on the password strength (when user is typing his password). They are
.weak {
    background-color: #F88E7D !important;
    border: 1px solid #F95D24 !important;
    width: 33.33% !important;
}

.medium {
    background-color: #FEE379 !important;
    border: 1px solid #EDB605 !important;
    width: 66.66% !important;
}

.strong {
    background-color: #81FF6C !important;
    border: 1px solid #05E428 !important;
    width: 101% !important;
}
The weak indicator reserves one-third of the progress bar's length. The medium and strong indicators reserve respectively two-thirds and all available space. The styling of the progress bar looks as follows:
.pwdStaerke.ui-progressbar {
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    margin-top: 8px;
    height: 18px !important;
    border: solid 1px #c2c2c2 !important;
}

.pwdStaerke.ui-progressbar .ui-progressbar-value {
    display: block !important;
    margin-left: -2px !important;
    -moz-border-radius: 6px !important;
    -webkit-border-radius: 6px !important;
    border-radius: 6px !important;
}

Tuesday, April 16, 2013

"Alway in view" paradigm in web

I was thinking about writing the next post in my blog and remembered one well-known paradigm I used in my completed web projects. The paradigm is to show current element(s) to be navigated always in view, that means visible. You know, a classic web application can have a long content causing scrollbars in browser. For instance, a vertical scrollbar means there is a hidden content - above or below the current viewport. Not only the browser, a div element can have scrollbars and a viewport as well (as long as the style overflow:hidden is not set). Keeping important element(s) always in view increases the usability. If an element, which is expected to be shown, doesn't stay visible, the user is often confused and forced to navigate the element manually. Just two examples with screenshots and jQuery based solutions.

Assume we have two tables. The first table on the left side shows users in a system. Rows are clickable. User's details for a clicked row are shown in the second table on the right side.


The left table is big and when we're scrolling down, at certain point we can not see the right table at all. Now, a row click in the left table updates the right table, but it might be hidden due to its small length.


Is it user friendly? No. To overcome this problem we will implement a jQuery function which checks if a specified element is beyond the visible area.
$.fn.showTopInView = function () {
    var winTop = $(window).scrollTop();
    var bounds = this.offset();

    if (winTop > bounds.top) {
        $('html, body').animate({scrollTop: 0}, 'fast');
    }
};
The .offset() method allows us to retrieve the current position of an element relative to the document. We compare element's top position with the amount we have scrolled from the topmost part of the page (calculated by $(window).scrollTop()). If the element (referenced with this) is located in the hidden area, its top position is less than this scrolled amount. In this case, we simple scroll to topmost part of the page with an animation. Using is simple. In our example, we should force execution of the following script when row clicking:
 
$('#IdOfTheRightTableContainer').showTopInView();
 
This can happen in onclick callback directly or streamed down as an JS script in response to the browser (if clicks cause AJAX requests). IdOfTheRightTableContainer is an Id of the div element the right table is placed in.

Another example is more complicated. As I said, scrollbars can also appear in div and hide inner elements. Assume again, we have a table included in such div container. The table displays some search results. e.g. documents and folders. Furthermore, assume we have thumbnails for every entry in this result table. User clicks on a thumbnail and want to see the related table's entry. The requirement thus - the table's entry of the selected thumbnail should be selected (highlighted) as well and should scroll to the div's viewport in order to always stay visible. The picture below demonstrates this behavior.


The script for solving this task uses the jQuery's method .position(). Other as .offset(), .position() retrieves the current position relative to the offset parent. The offset parent should be positioned (position: absolute or relative). In our example the offset parent is a relative positioned div element with the style class ui-layout-content (note: the web app used the jQuery Layout plugin). First, we need to write a function which will find the table's entry by some given identifier (here pid argument). This function gets invoked when user clicks on a thumbnail.
function selectResultEntryOnCurrentPage (pid) {
    var $resultTable = $("#searchResultTable");
    var $resultEntry = $resultTable.find(".resultEntry[data-pid='" + pid + "']");
    $resultTable.find(".resultEntry").removeClass("selected");
    $resultEntry.addClass("selected");
    
    scrollToResultEntry ($resultTable, $resultEntry);
}
What we did here, was only a row selection. The table and the found table's entry are passed as parameters into the next function scrollToResultEntry. This function is responsible for keeping the selected entry visible.
function scrollToResultEntry ($resultTable, $resultEntry) {
    // scroll to the entry with animation if it's not completely visible
    var $scrollPane = $resultTable.closest(".ui-layout-content");
    var entryPos = $resultEntry.position();
    if (entryPos.top < 0) {
        // element has parts in the hidden top area of the scrollable layout pane ==> scroll up
        $scrollPane.animate({scrollTop: $scrollPane.scrollTop() + entryPos.top - 5}, "fast");
    } else if ($scrollPane.height() < entryPos.top + $resultEntry.outerHeight()) {
        // element has parts in the hidden bottom area of the scrollable layout pane ==> scroll down
        $scrollPane.animate({
            scrollTop: $scrollPane.scrollTop() + $resultEntry.outerHeight() + (entryPos.top - $scrollPane.height()) + 5}, "fast");
    }    
}
We measure the top position of the selected table's entry. Negative value means the entry is not completely visible and has some parts in the top area of the scrollable div (the mentioned offset parent). The second condition $scrollPane.height() < entryPos.top + $resultEntry.outerHeight() means the entry is not completely visible and has some parts in the bottom area of the scrollable div. In both cases, the entry is scrolled to the div's viewport with an animation. The new vertical scroll position is calculated (a little bit tricky) and set in the scrollTop option.

Monday, February 4, 2013

How to prevent tab changing in PrimeFaces TabView when validation failed

Trying various approaches to the question above (with p:ajax event="tabChange" and so on), I came up with a clean and well working solution. The code below turns on the PrimeFaces TabView into a "wizard mode". That means, the user stays on the same tab when he / she is trying to switch tabs and has validation errors within the current tab. The main idea is to use p:remoteCommand for a deferred decision about tab switching. If no validation errors were present, the switching occurs by the TabView widget's method select.

XHTML
<p:tabView ... widgetVar="tv_widget" styleClass="tv_selector">
    ...
</p:tabView>
           
<p:remoteCommand name="tv_remoteCommand" process="@(.tv_selector)" update="@(.tv_selector)" global="false"
        oncomplete="handleTabChangeTV(xhr, status, args, tv_widget)"/>
           
<h:panelGroup id="tv_script" styleClass="tv_selector">
    <script type="text/javascript">
          $(function(){
              bindOnClickTV(tv_remoteCommand, tv_widget);
          });
    </script>
</h:panelGroup>
JavaScript
function bindOnClickTV(rc, widget) {
    // unbind PrimeFaces click handler and bind our own
    widget.jq.find('.ui-tabs-nav > li').unbind('click.tabview').
        off('click.custom-tabview').on('click.custom-tabview', function (e) {
            var element = $(this);
       
            if ($(e.target).is(':not(.ui-icon-close)')) {
                var index = element.index();
       
                if (!element.hasClass('ui-state-disabled') && index != widget.cfg.selected) {
                    // buffer clicked tab
                    widget.clickedTab = element.index();
       
                    // call remote command
                    rc();
                }
            }
       
            e.preventDefault();
        });
}

function handleTabChangeTV(xhr, status, args, widget) {
    if (!args.validationFailed) {
        widget.select(widget.clickedTab);
    }
}

Thursday, December 6, 2012

Register hotkeys for PrimeFaces dialogs

In this blog post I would like to share a jQuery based (low level), fast working solution to register hotkeys for PrimeFaces dialogs. Why do we need this low level solution? Primary because the PrimeFaces component p:hotkey doesn't work as expected in dialogs. We were only interested in two hotkeys ESC and ENTER, so that I will only show a solution for these two hotkeys.

Requirements: When user presses the ESC key, a dialog should be closed. When user presses the ENTER key, the dialog action should be submitted (imagine e.g. a "Are you sure you want to delete?" dialog). Dialog can look like as follows. In the real world it is better to please the dialog into a composite component in order to reuse it.
<p:confirmDialog header="Confirmation" widgetVar="confirmDlgWidget" appendToBody="true">
  <f:facet name="message">
     ...
  </f:facet>
  <h:form>
    <p:commandButton value="OK" process="@this" update="..." action="..." oncomplete="confirmDlgWidget.hide();"/>
    <p:commandButton value="Cancel" onclick="confirmDlgWidget.hide();" type="button"/>
  </h:form>
</p:confirmDialog>
After the dialog tag, the following short JS script should be placed.
<script type="text/javascript">
 /* <![CDATA[ */
 $(function () {
    registerConfirmDialogHotkeys(confirmDlgWidget);
 });
 /* ]]> */
</script>
The JS function itself is located in a file. Here how it was implemented:
function registerConfirmDialogHotkeys(dlgWidget) {

    var key = 'keydown.pfdialog_' + dlgWidget.id;

    $(document).off(key).on(key, function (e) {
        var keyCode = $.ui.keyCode;
        var active = parseInt(dlgWidget.jq.css('z-index')) === PrimeFaces.zindex;

        if (dlgWidget.jq.hasClass('ui-overlay-visible') && active) {
            if (e.which === keyCode.ESCAPE) {
                dlgWidget.hide();
            } else if (e.which === keyCode.ENTER || e.which == keyCode.NUMPAD_ENTER) {
                dlgWidget.jq.find('button:submit:first').click();
                e.preventDefault();
            }
        }
    });
}
The function registers a namespaced keydown JS callback on document. The callback checks if the dialog is active currently. This is normally a last opened dialog. If it is active and the user has pressed ESC, then hide the dialog (widget variable is passed into the function). If it is active and the user has pressed ENTER, then find the first submit button within this dialog and click it to cause an action execution. That's all.

Thursday, March 22, 2012

High Performance Webapps. jQuery Objects as Arrays.

After recently participation in a workshop Real Life JS: High Performance Webapps. I have decided to share some tricks to achieve better perfomance for websites. There are 100+ tricks. It's impossible to covers all of them. In this post I would like to show a difference between using of jQuery calls and JavaScript native ones. Especially using of $.each() method for iteration is the topic of this post. I already knew that using of $.each() is slow. This fact is described in 15 Powerful jQuery Tips and Tricks for Developers (chapter 3). What is an alternative to $.each()? How to iterate faster on result set of running a selector? The result of running a selector is an jQuery object. However, the library makes it appear as if you are working with an array by defining index elements and a length. Use a native JavaScript for or while loop on the result. Check this example please. Perfomance benefit is huge in my opinion. I also learned that any method call in JavaScript brings a lot of overhead. I also learned that literal notation like this one
var myArray = [];
var newElement = "test element";
myArray[myArray.length] = newElement;
always works faster than
var myArray = new Array();
var newElement = "test element";
myArray.push(newElement);
Never call new operator if you can use literal notations for arrays and objects in JavaScript. Never call methods like push() if you can do this in another way. Difference in execution time of the code parts above is significant in loops. The main rule here: "Less operations per iteration - less execution time. Doing nothing is the best from performance point of view". An example of bad programming would be
for(var i=0; i < myArray.length; i++) {
    ...
}
because length is not cached and myArray.length is executed for each iteration step.

Today, I've played a little bit with the new great feature in PrimeFaces jQuery Selector API meets JSF. My aim was to compare $.each(), array's push() and $.attr() calls with native JavaScript calls. I prepared a small test page with a simple selector and the code from PrimeFaces core.js. Alternative I rewritten the code in PrimeFaces with native calls to show the difference. First, I ended up with this code. The main code is here:
var selector = "@(ul li)";
var jqSelector = selector.substring(2, selector.length - 1);
var components = $(jqSelector);
var ids = [];

console.time('Native Loop');
var length = components.length;
for(var i=0; i < length; i++) {
    ids[length] = $(components[i]).attr('id');
}
console.timeEnd('Native Loop');

console.time('jQuery Each');
components.each(function() {
    ids.push($(this).attr('id'));
});
console.timeEnd('jQuery Each');
My Firefox 11 shown (average time):

Native Loop : 28 ms
jQuery Each : 37 ms

IE8 shown:

Native Loop : 249 ms
jQuery Each : 281 ms

After that I deleted $ around components[i] in the for loop and replaced $.attr('id') by native .getAttribute('id') (what I always use in my not jQuery / JSF apps). Changes:
var length = components.length;
for(var i=0; i < length; i++) {
    ids[length] = components[i].getAttribute('id');
}
Look this test page please. Now we have in Firefox 11:

Native Loop : 3 ms
jQuery Each : 42 ms

and in IE8:

Native Loop : 14 ms
jQuery Each : 274 ms

Perfomance benefit in IE8 (with choosen selector) is 260 ms. Not bad. This trick can give more performance optimization in a huge page. I'm not a game developer and don't develop critical web applications. But a performance optimization is always good for me anyway. Optimization means not only CSS and JavaScript optimization. Loading of images / icons can be optimized as well. Next post(s) will cover more such stuff.

Thursday, August 25, 2011

Combine jQuery Datepicker and Spinner for fast day incrementation / decrementation

Is it possible to add + / - buttons to jQuery UI Datepicker in order to increment / decrement days in a comfortable way? Yes, it's possible. I have done this task - see screenshot.


This is an extended PrimeFaces Calendar with added "dateSpinner" mode. I would like to omit JSF part and only show HTML / CSS / JavaScript part of such combined calendar. All what you need is to wrap the datepicker markup with a span element, add themable up / down arrows and use datepicker utility functions $.datepicker.formatDate(format, date, settings) and $.datepicker.parseDate(format, value, settings).

HTML
Original HTML with a calendar icon (called icon trigger in jQuery Datepicker) looks very simple
 
<input id="datepicker" class="hasDatepicker" type="text">
<img class="ui-datepicker-trigger" src="images/calendar.gif" alt="..." title="...">
 
You have to extend this as follows
<span id="datepickerWrapper" class="ui-ccalendar ui-widget ui-corner-all">
	<input id="datepicker" class="hasDatepicker" type="text">
	<img class="ui-datepicker-trigger" src="images/calendar.gif" alt="..." title="...">
	<a class="ui-ccalendar-button ui-ccalendar-up ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only">
		<span class="ui-button-text">
			<span class="ui-icon ui-icon-triangle-1-n"></span>
		</span>
	</a>
	<a class="ui-ccalendar-button ui-ccalendar-down ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only">
		<span class="ui-button-text">
			<span class="ui-icon ui-icon-triangle-1-s"></span>
		</span>
	</a>
</span>

CSS
The most CSS classes above are jQuery UI classes. I marked own classes with ui-ccalendar. In the CSS part is very important to shift spinner's arrow buttons to left. I have shifted absolute positioned buttons with CSS statement right: 17px;. We achieve with this displacement that the calendar icon is visible.
.ui-ccalendar {
    display: inline-block;
    overflow: visible;
    padding: 0;
    position: relative;
    vertical-align: middle;
}

.ui-ccalendar-button {
    cursor: default;
    display: block;
    font-size: 0.5em;
    height: 50%;
    margin: 0;
    overflow: hidden;
    padding: 0;
    position: absolute;
    right: 17px;
    text-align: center;
    vertical-align: middle;
    width: 16px;
    z-index: 100;
}

.ui-ccalendar .ui-icon {
    left: 0;
    margin-top: -8px;
    position: absolute;
    top: 50%;
}

.ui-ccalendar-up {
    top: 0;
}

.ui-ccalendar-down {
    bottom: 0;
}

.ui-ccalendar .ui-icon-triangle-1-s {
    background-position: -65px -16px;
}

.ui-ccalendar .ui-icon-triangle-1-n {
    margin-top: -9px;
}

JavaScript
In this part I use the mentioned above utility functions formatDate() / parseDate() and setDate() / getDate() API of Date object to increment / decrement a single day. Month and year boundaries are considered automatically and in- / decremented if necessary. In- / decrementation logic is bound to mousedown event on spinner buttons.
var datepickerInput = $('#datepicker');
datepickerInput.datepicker({dateFormat: 'yy-mm-dd', ... other configuration if needed ...});

$('#datepickerWrapper').children('.ui-ccalendar-button').mouseover(function() {
	$(this).addClass('ui-state-hover');
}).mouseout(function() {
	$(this).removeClass('ui-state-hover');
}).mouseup(function() {
	$(this).removeClass('ui-state-active');
}).mousedown(function() {
	var el = $(this);
	el.addClass('ui-state-active');
	try {
		// get configured date format
		var dateFormat = datepickerInput.datepicker("option", "dateFormat");

		// extract a date from a string value with a specified format
		var date = $.datepicker.parseDate(dateFormat, datepickerInput.val());
		if (el.hasClass('ui-ccalendar-up')) {
			// increment day
			date.setDate(date.getDate() + 1);
		} else {
			// decrement day
			date.setDate(date.getDate() - 1);
		}

		// format a date into a string value with a specified format
		var strDate = $.datepicker.formatDate(dateFormat, date);
		datepickerInput.val(strDate);
	} catch (err) {
		// ignore and nothing to do
	}
});
Important is here "dateFormat" option. Date format normally depends on user locale and should be passed from outside.

P.S. Just now I found a desktop example of such combined calendar too. So, you see, it's an useful and established widget :-).

Wednesday, July 13, 2011

Filter keyboard input of JSF input components

jQuery keyfilter plugin is a good choice if you want to filter input by specified regular expression. It allows you to input only specified characters via regular expression. Assume, your input field has an ID "myinput" and you want to restrict any user input to hexadecimal characters. This task can be done as follows
 
$('#myinput').keyfilter(/[0-9a-f]/i);
 
You can also pass a test function instead of regular expression. It expects two arguments: event target (DOM element) and incoming character. If the return value is true, the input character is valid and allowed, otherwise - not.
 
$('#myinput').keyfilter(function(c) {
    return c != 'a';
});
 
Easy? There are a lot of predefined masks too - for numeric, alphanumeric, etc. signs. Do we have something like in JSF? No. Well, there is a component MaskedInput in PrimeFaces, but it's restricted to a fix length. Length of the input value can not be variable and there is a very small set of signs to configure input masks. Conclusion - poor component :-). Keyfilter covers MaskedInput and offers more flexibility. Can we implement the keyfilter functionality in JSF? Yes, ideally as client behavior. The aim of this post is not this implementation. The aim of this topic is to show how to attach this functionality to an existing JSF component (hard-coded). I would like to take PrimeFaces AutoComplete. I would also like to show a tooltip if user input some disallowed characters. Let's start. We extend the component class by adding new resources - CSS and JS files for jQuery tooltip (qTip2), keyfilter plugins and an own extension for the AutoComplete widget.
@ResourceDependencies({
    @ResourceDependency(library="primefaces", name="forms/forms.css"),
    @ResourceDependency(library="primefaces", name="jquery/ui/jquery-ui.css"),
    @ResourceDependency(library="primefaces", name="jquery/jquery.js"),
    @ResourceDependency(library="primefaces", name="jquery/ui/jquery-ui.js"),
    @ResourceDependency(library="primefaces", name="core/core.js"),
    @ResourceDependency(library="primefaces", name="autocomplete/autocomplete.js"),
    @ResourceDependency(library = "css", name = "jquery.qtip.css"),
    @ResourceDependency(library = "js", name = "tooltip/jquery.qtip.js"),
    @ResourceDependency(library = "js", name = "autocomplete/jquery.keyfilter.js"),
    @ResourceDependency(library = "js", name = "autocomplete/autocomplete.js")
})
public class AutoComplete extends org.primefaces.component.autocomplete.AutoComplete {
}
In the AutoCompleteRenderer.java we add these lines to encodeScript()
// get tooltip text for invalid characters
String tooltipText = MessageUtils.getMessageText(facesContext,
    facesContext.getApplication().getMessageBundle(), "autocomplete.invalidChars");
if (tooltipText != null) {
    tooltipText = tooltipText.replaceAll("'", "\\\\'");
} else {
    // fallback
    tooltipText = "Input character is not allowed";
}
writer.write(",tooltipText:'" + tooltipText + "'");
I used here an own utility class MessageUtils to get a message from message bundle. The most complicated step is the writing of an extended widget.
PrimeFaces.widget.ExtendedAutoComplete = function(id, cfg) {
    this.superWidget = PrimeFaces.widget.AutoComplete;
    this.superWidget(id, cfg);
    var _self = this;

    // initialize flag whether the current input character is valid
    this.jq.data("allowedChar", true);

    // define tooltip
    this.jq.qtip({
        content: {
            text: cfg.tooltipText
        },
        style: {
            widget: true,
            classes: 'ui-tooltip-rounded ui-tooltip-shadow'
        },
        position: {
            my: 'bottom center',
            at: 'top center'
        },
        events: {
            show: function(event, api) {
                try {
                    if (_self.jq.data("allowedChar")) {
                        event.preventDefault();
                    }
                } catch(e) {
                    // IE can throw an error
                }
            },
            hide: function(event, api) {
                _self.jq.data("allowedChar", true);
            }
        },
        show: {
            event: false
        },
        hide: {
            event: 'blur'
        }
    });

    // filter input
    this.filterKeys(cfg);
}

jQuery.extend(PrimeFaces.widget.ExtendedAutoComplete.prototype, PrimeFaces.widget.AutoComplete.prototype);

PrimeFaces.widget.ExtendedAutoComplete.prototype.filterKeys = function(cfg) {
    var _self = this;

    _self.jq.keyfilter(function(c) {
        var isAllow = _self.allowChar(c);
        _self.jq.data("allowedChar", isAllow);

        if (cfg.pojo) {
            _self.jq.unbind('keyup');
        }

        if (isAllow) {
            // hide tooltip
            _self.jq.qtip('hide');

            if (cfg.pojo) {
                _self.jq.keyup(function(e) {
                    if (e.keyCode != 13) {
                        jQuery(_self.jqh).val(jQuery(this).val());
                    }
                });
            }
        } else {
            // show tooltip
            _self.jq.qtip('show');
        }

        return isAllow;
    });
}

PrimeFaces.widget.ExtendedAutoComplete.prototype.allowChar = function(c) {
    return c != '%' && c != '?' && c != '&';
}
I wrote here a test function instead of regular expression to prevent % ? & signs to be input. The result looks pretty fine

Thursday, June 30, 2011

Global tooltips with PrimeFaces and qTip2

PrimeFaces uses jQuery qTip plugin in the version 1 for global tooltips which are applied to all HTML elements having title attribute. There is an issue with ajax updates - global tooltips with qTip1 are gone after an ajax update. An ajax update of any element having the title attribute causes disappearance of nice tooltip. Native tooltips are still here but they are very plain, not beautiful and not themes aware. The official statement from the PrimeFaces team - "known issue, won't be fixed for global ones at the moment". In this post you will see how to resolve this issue in the simple way. The first step is to upgrade the qTip plugin to qTip2 and write a component class. The component class extends PrimeFaces' one and overwrites all methods what tooltip's default values have been changed for.
@ResourceDependencies({
    @ResourceDependency(library="primefaces", name="jquery/jquery.js"),
    @ResourceDependency(library="primefaces", name="core/core.js"),
    @ResourceDependency(library = "css", name = "jquery.qtip.css"),
    @ResourceDependency(library = "js", name = "tooltip/jquery.qtip.js"),
    @ResourceDependency(library = "js", name = "tooltip/tooltip.js")
})
public class Tooltip extends org.primefaces.component.tooltip.Tooltip
{
    public java.lang.String getTargetPosition() {
        return (java.lang.String) getStateHelper().eval(PropertyKeys.targetPosition, "bottom right");
    }

    public java.lang.String getPosition() {
        return (java.lang.String) getStateHelper().eval(PropertyKeys.position, "top left");
    }

    public java.lang.String getShowEffect() {
        return (java.lang.String) getStateHelper().eval(PropertyKeys.showEffect, "fadeIn");
    }

    public java.lang.String getHideEffect() {
        return (java.lang.String) getStateHelper().eval(PropertyKeys.hideEffect, "fadeOut");
    }

    public java.lang.String getShowEvent() {
        return (java.lang.String) getStateHelper().eval(PropertyKeys.showEvent, "mouseenter");
    }

    public java.lang.String getHideEvent() {
        return (java.lang.String) getStateHelper().eval(PropertyKeys.hideEvent, "mouseleave");
    }    
}
jquery.qtip.js is a new qTip script placed under the folder webapp/resources/js/tooltip and the tooltip.js is our one. In the tooltip.js I use the jQuery .live() method playing together with qTip2. This method allows us to easily add qTips to certain elements on a page, even when updating the DOM and adding new elements.
PrimeFaces.widget.Tooltip = function(cfg) {
    this.cfg = cfg;
    var _self = this;

    if (this.cfg.global) {
        // Bind the qTip within the event handler
        jQuery('*[title]').live(this.cfg.show.event, function(event) {
            var extCfg = _self.cfg;
            // Show the tooltip as soon as it's bound
            extCfg.show.ready = true;
            jQuery(this).qtip(extCfg, event);
        });
    } else {
        jQuery(PrimeFaces.escapeClientId(this.cfg.forComponent)).qtip(this.cfg);
    }
}

// make tooltip theme aware
jQuery.fn.qtip.defaults.style.widget = true;
jQuery.fn.qtip.defaults.style.classes = "ui-tooltip-rounded ui-tooltip-shadow";
jQuery ThemeRoller integration is done by the last two lines. The last step is to extend PrimeFaces's TooltipRenderer (because tooltip API has been changed) and register then all stuff in the faces-config.xml
public class TooltipRenderer extends org.primefaces.component.tooltip.TooltipRenderer
{
    public void encodeEnd(FacesContext facesContext, UIComponent component) throws IOException {
        Tooltip tooltip = (Tooltip) component;

        // dummy markup for ajax update (not really necessary)
        ResponseWriter writer = facesContext.getResponseWriter();
        writer.startElement("span", tooltip);
        writer.writeAttribute("id", tooltip.getClientId(facesContext), "id");
        writer.endElement("span");

        encodeScript(facesContext, tooltip);
    }

    protected void encodeScript(FacesContext facesContext, org.primefaces.component.tooltip.Tooltip tp)
        throws IOException {
        Tooltip tooltip = (Tooltip) tp;
        ResponseWriter writer = facesContext.getResponseWriter();
        boolean global = tooltip.isGlobal();
        String owner = getTarget(facesContext, tooltip);

        writer.startElement("script", null);
        writer.writeAttribute("type", "text/javascript", null);

        writer.write("jQuery(function() {");
        writer.write(tooltip.resolveWidgetVar() + " = new PrimeFaces.widget.Tooltip({");
        writer.write("global:" + global);

        if (!global) {
            writer.write(",forComponent:'" + owner + "'");
            writer.write(",content:'");
            if (tooltip.getValue() == null) {
                renderChildren(facesContext, tooltip);
            } else {
                writer.write(ComponentUtils.getStringValueToRender(facesContext, tooltip).replaceAll("'", "\\\\'"));
            }
            writer.write("'");
        }

        writer.write(",show:{event:'" + tooltip.getShowEvent() + "',delay:" + tooltip.getShowDelay() + 
            ",effect:function(){jQuery(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength() + ");}}");
        writer.write(",hide:{event:'" + tooltip.getHideEvent() + "',delay:" + tooltip.getHideDelay() + 
            ",effect:function(){jQuery(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength() + ");}}");
        writer.write(",position: {");
        String container = owner == null ? 
            "jQuery(document.body)" : "jQuery(PrimeFaces.escapeClientId('" + owner + "')).parent()";
        writer.write("container:" + container);
        writer.write(",at:'" + tooltip.getTargetPosition() + "'");
        writer.write(",my:'" + tooltip.getPosition() + "'");
        writer.write("}});});");

        writer.endElement("script");
    }
}
Have much fun! In one of my next post I will explain how to show a nice tooltip attached to the PrimeFaces Autocomplete component if user input disallowed characters.

Edit: I think a binding with namespace would be better to avoid collisions. Furthermore, a call of .die() before .live() is necessary in order to prevent miltiply binding of the same event if the tooltip gets updated via ajax. The same is for non global tooltips
jQuery('*[title]').die(this.cfg.show.event + ".tooltip").live(this.cfg.show.event + ".tooltip", ...
    ...
});

... in else ...

// delete previous tooltip to support ajax updates and create a new one
jQuery(PrimeFaces.escapeClientId(this.cfg.forComponent)).qtip('destroy').qtip(this.cfg);
The container element which the tooltip is appended to should be always document.body in order to play nice with layout, datatable, etc. Changes in TooltipRenderer.java:
writer.write("container:jQuery(document.body)");

Wednesday, June 8, 2011

Client-side validation with jQuery validation plugin. Advanced examples.

In the last post I covered the basics of the great jQuery validation plugin - state-of-the-art for client-side validation. I'm going to show now an advanced example how to write validation rules, own validation methods and put all together. I'm writing a collaborative whiteboard just now and needed two dialogs placed in the same HTML form. My task were:

1) Write a dialog to input a valid image URL, image width and height. This dialog looks as follows


and was written in JSF (PrimeFaces) as
<p:dialog id="dialogInputImage" header="Input image URL" resizable="false" closable="true" modal="true" styleClass="validatable">
    <ul id="errorImageUl" class="errormsg"/>
    <h:panelGrid id="dlgImageGrid" columns="2" columnClasses="...">
        <h:outputLabel value="Image URL" for="inputUrl"/>
        <p:inputText id="inputUrl"/>
        <h:outputLabel value="Image width (px)" for="imgWidth"/>
        <h:panelGroup>
            <p:inputText id="imgWidth" maxlength="4"/>
            <h:outputLabel value="Image height (px)" for="imgHeight" style="margin: 0 10px 0 10px;"/>
            <p:inputText id="imgHeight" maxlength="4"/>
        </h:panelGroup>
    </h:panelGrid>
</p:dialog>

2) Write a second dialog with input fields for whiteboard width and height. This dialog looks as follows


and was written in JSF (PrimeFaces) as
<p:dialog id="dialogResize" header="Resize Whiteboard" resizable="false" closable="true" modal="true" styleClass="validatable">
    <ul id="errorResizeUl" class="errormsg"/>
    <h:panelGrid id="dlgResizeGrid" columns="4" columnClasses="...">
        <h:outputLabel value="Whiteboard width (px)" for="wbWidth"/>
        <p:inputText id="wbWidth" maxlength="4"/>
        <h:outputLabel value="Whiteboard height (px)" for="wbHeight"/>
        <p:inputText id="wbHeight" maxlength="4"/>
    </h:panelGrid>
</p:dialog>

3) Validation requirements:

First dialog.
- If nothing was input (all fields are empty) ==> no validation for all fields.
- If the URL field is empty ==> no validation for all fields.
- If the URL field is not empty ==> check if the URL is valid and input image width / height are positive digits (greater than 0).

Second dialog.
- Always check input width and height which should be positive digits (greater than 0).

Furthermore, error messages should be groupped. I use "errorPlacement" option for this. We need an error container to play nice with "errorPlacement". Therefore, I defined an error container in each dialog by UL element which will contain LI elements if any errors occur.
 
<ul id="..." class="errormsg"/>
 
Let me show the JavaScript part now. Comments help to understand the logic behind my code. The code should be placed after all p:dialog tags
jQuery(function() {
    // add a new validation method to validate image width / height
    jQuery.validator.addMethod("imageSize", function(value, element, param) {
        // check parameter "#inputUrl:filled" (see validate(...) method below) 
        if (jQuery.find(param).length < 1) {
            return true;
        }

        // use built-in "digits" validator and check if digits are positive
        return !this.optional(element) && jQuery.validator.methods['digits'].call(this, value, element) && parseInt(value) > 0;
    }, "Please enter a valid image size (only positive digits are allowed).");

    // create an object with rules for convenience (using in validate(...))
    var dimensionRules = {
        required: true,
        digits: true,
        min: 1
    };

    // create a validator with rules for all dialog fields
    dialogValidator = jQuery("#mainForm").validate({
        // validation is on demand ==> set onfocusout and onkeyup validation to false
        onfocusout: false,
        onkeyup: false,
        errorPlacement: function(label, elem) {
            elem.closest(".validatable").find(".errormsg").append(label);
        },
        wrapper: "li",
        rules: {
            inputUrl: {
                url: true
            },
            imgWidth: {
                // validation of image size depends on input URL - validate size for not empty URL only
                imageSize: "#inputUrl:filled"
            },
            imgHeight: {
                // validation of image size depends on input URL - validate size for not empty URL only
                imageSize: "#inputUrl:filled"
            },
            wbWidth: dimensionRules,
            wbHeight: dimensionRules
        },
        messages: {
            // define validation messages
            inputUrl: "Please enter a valid image URL.",
            imgWidth: "Please enter a valid image width (only positive digits are allowed).",
            imgHeight: "Please enter a valid image height (only positive digits are allowed).",
            wbWidth: "Please enter a valid whiteboard width (only positive digits are allowed).",
            wbHeight: "Please enter a valid whiteboard height (only positive digits are allowed)."
        }
    });

    // configure the first dialog
    jQuery("#dialogInputImage").dialog("option", "buttons", {
        "Accept": function() {
            // validate all fields if user click on the "Accept" button
            var isValid1 = dialogValidator.element("#inputUrl");
            var isValid2 = dialogValidator.element("#imgWidth");
            var isValid3 = dialogValidator.element("#imgHeight");

            if ((typeof isValid1 !== 'undefined' && !isValid1) || (typeof isValid2 !== 'undefined' && !isValid2) ||
               (typeof isValid3 !== 'undefined' && !isValid3)) {
                // validation failed
                return false;
            }

            // do something ...
        },
        "Close": function() {
            jQuery(this).dialog("close");
        }
    }).bind("dialogclose", function(event, ui) {
        // reset input
        jQuery(this).find("#inputUrl").val('');
        // clean up validation messages
        jQuery("#errorImageUl").html('');
    });

    // configure the second dialog
    jQuery("#dialogResize").dialog("option", "buttons", {
        "Accept": function() {
            // validate all fields if user click on the "Accept" button
            var isValid1 = dialogValidator.element("#wbWidth");
            var isValid2 = dialogValidator.element("#wbHeight");

            if ((typeof isValid1 !== 'undefined' && !isValid1) || (typeof isValid2 !== 'undefined' && !isValid2)) {
                // validation failed
                return false;
            }

            // do something ...

            jq.dialog("close");
            
            // do something ...
        },
        "Close": function() {
            jQuery(this).dialog("close");
        }
    }).bind("dialogclose", function(event, ui) {
        // clean up validation messages
        jQuery("#errorResizeUl").html('');
    });
});
Validation looks now as follows



 In fact I already implemented partially client-side validation as JSF components ;-).

Saturday, June 4, 2011

Client-side validation with jQuery validation plugin. Basic concepts.

jQuery validation plugin is my favorite framework for client-side validation. I'm surprised more and more about its power and flexibility. Before I start to describe my recently task for client-side validation I would like to say few words how this plugin works at all. jQuery validation plugin has a predefined set of validation methods for required fields, emails, URLs, credit card, numbers, dates, etc. All bundled methods come with default error messages in english and translations into 32+ languages. By default, error messages are displayed after the invalid element, but this is also customizable. It is also possible to put them into an error container at some other places and show them bundled all together. Desired validation methods can be specified in two ways:

1) By HTML "class" attribute.
2) By rules in JavaScript.

The first way is simple. Assume, you have a form with Id "registerForm" containing fields "Name" and "E-mail". Both fields should be required. In additional, the field "Name" requires minimum 3 letters and the field "E-mail" accepts only valid e-mail inputs.
<form id="registerForm" method="get" action="...">
    <label for="name">Name</label>
    <input id="name" name="name" size="25" class="required" minlength="3" />
    <label for="email">E-Mail</label>
    <input id="email" name="email" size="25" class="required email" />
</form>
Validation methods are specified here by "class" attributes. The form can be validated now by the call
 
jQuery("#registerForm").validate();
 
How does this plugin behave? By default, forms are validated on submit, triggered by the user clicking the submit button or pressing enter when a form input is focused. There is also validation on single elements on demand.
var validator;

jQuery(document).ready(function(){
     validator = jQuery("#registerForm").validate();
     ...
     doSomething();
});

function doSomething() {
    var isNameValid = validator.element("#name");
    if (isNameValid) {
        // do something
        ...
    }
}
The call validator.element("#name") above validates a single field "Name" and returns true if it is valid, false otherwise.

Before submitting the form for the first time the validation is lazy. The user can tab through fields without getting annoying messages. He has a chance to correct input values. Once a field was marked invalid, it is eagerly validated. The plugin validates on keyup if the user types something. When the user enters something invalid into a valid field, it is also validated when the field loses focus (onblur). In addition, a field can be highlighted as invalid. As soon as the user entered the necessary value, the error message is removed.

I prefer the second way - validation by rules definitions via JavaScript. This is more flexible and leaves nothing to be desired - there are many configuration parameters. Rules and messages can be configured in the validate(...) method. Each rule specifies Id of the field to be validated and desired validation methods for this field.
jQuery("#registerForm").validate({
    rules: {
        name: {
            required: true,
            minlength: 3
        },
        email: {
            required: true,
            email: true
        }
    },
    messages: {
        name: "Please enter a valid name.",
        email: "Please enter a valid e-mail."
    }
});
Rules can be added dynamically too after validate() was called. Like this one for the field with Id "name" above.
 
jQuery("#name").rules("add", {minlength: 3});
 
Validation methods can be grouped as one. For example if you want to group all three built-in validation methods "required", "date" and "dateRange", you can write
jQuery.validator.addClassRules({
    requiredDateRange: {required:true, date:true, dateRange:true}
});
The new validation method is called now "requiredDateRange". Another nice feature - overwriting of default messages. Example for "required" and "date" validations:
jQuery.extend(jQuery.validator.messages, {
    required: "These fields are required",
    date: "Please specify valid dates"
});
Last but not least - adding of new validation methods by
 
jQuery.validator.addMethod(name, method, [message]);
 
In the next post I will show an example for jQuery.validator.addMethod and more other advanced tricks. Stay tuned.

Thursday, May 26, 2011

Auto sized jQuery UI dialogs and PrimeFaces

jQuery (modal) dialog causes some problems in Internet Explorer like scrollbars on page and not working auto width. See e.g. tickets http://bugs.jqueryui.com/ticket/3623 and http://bugs.jqueryui.com/ticket/4437. width:auto is very important for most dialogs because you often don't know how large the dialog's content is (think e.g. about multi-language labels). General you will not get problems with width:auto and can write
<div id="dialog" title="My dialog">
  ... content ...
</div>

$('#dialog').dialog({
    modal: true,
    height: 'auto',
    width: 'auto'
});
or define CSS class
.autoWidthDialog {
    width: auto !important;
}
and write in PrimeFaces
<p:dialog id="dialog" styleClass="autoWidthDialog" header="My dialog">
  ... content ...
</p:dialog>
Working well except one problem - broken dialog's header in IE7 and below. Titelbar is shrunk to the title text length. Unfortunately, jQuery team doesn't want to fix this issue and support flexible dialogs with width:auto, so that a workaround is needed. Annoying scrollbars on page for modal dialogs should be fixed too. I came up with the following solution:

Native jQuery UI dialog:
jQuery("#dialog").dialog({
    modal: true,
    height: 'auto',
    width: 'auto'
    ... other various options ...
}).bind("dialogopen", function(event, ui) {
    // fix for width:auto in IE
    var jqDialog = jQuery(this);
    var parent = jqDialog.parent();
    var contentWidth = jqDialog.width();
    parent.find('.ui-dialog-titlebar').each(function() {
        jQuery(this).width(contentWidth);
    });
    parent.width(contentWidth + 26);
    jqDialog.dialog('option', 'position', 'center');

    // fix for scrollbars in IE
    jQuery('body').css('overflow', 'hidden');
    jQuery('.ui-widget-overlay').css('width', '100%');
}).bind("dialogclose", function(event, ui) {
    // fix for width:auto in IE
    jQuery(this).parent().css("width", "auto");

    // fix for scrollbars in IE
    jQuery('body').css('overflow', 'auto');
});
PrimeFaces dialog built on the top of native one:
<p:dialog id="dialog" styleClass="autoWidthDialog"
          onShow="onShowAutoWidthDialog(this.jq);"
          onHide="onHideAutoWidthDialog(this.jq);">
  ... content ...
</p:dialog>
function onShowAutoWidthDialog(jqDialog) {
    // fix for auto width in IE
    var parent = jqDialog.parent();
    var contentWidth = jqDialog.width();
    parent.find('.ui-dialog-titlebar').each(function() {
        jQuery(this).width(contentWidth);

    });
    parent.removeClass("autoWidthDialog").width(contentWidth + 26);
    jqDialog.dialog('option', 'position', 'center');

    // fix for scrollbars in IE
    jQuery('body').css('overflow', 'hidden');
    jQuery('.ui-widget-overlay').css('width', '100%');
}

function onHideAutoWidthDialog(jqDialog) {
    // fix for auto width in IE
    var parent = jqDialog.parent();
    parent.find('.ui-dialog-titlebar').each(function() {
        // reset titlebar width
        jQuery(this).css('width', '');
    });
    parent.addClass("autoWidthDialog");

    // fix for scrollbars in IE
    jQuery('body').css('overflow', 'auto');
}
I use onShow / onHide client side callbacks. Settings onShow="onShowAutoWidthDialog(this.jq);" onHide="onHideAutoWidthDialog(this.jq);" fix mentioned above IE issues. Unfortunately, PrimeFaces p:confirmDialog doesn't have these attributes (why?), so that I had to add onShow / onHide to p:confirmDialog similar to p:dialog. Component / renderer classes can be easy extended and for JavaScript widget I can post the code if somebody needs it. :-)

Edit: There isn't cross-browser pure CSS solution; I didn't find it and didn't see anywhere.

Sunday, May 8, 2011

Prevent multiple clicks in JSF

Preventation of multiple clicks on buttons / links is a common and important task during web development. There are many discussions about double click problem in JSF I will try to cover all relevant approaches.

1) Server-side solution.
Server-side solutions are normally based on token concept, phase listeners, filters or other complex tricks. Here is just one example for the server-side preventation of double-form submit Server-side solutions have disadvantages. Every request is handled by a special phase listener, filter or something near it, even if we are not interesting in multiple clicks preventation. There are problems in a cluster environment if session data get replicated. This a real problem I faced many years ago - our server-side solution didn't work proper if the web application was running in a cluster environment. Client-side solutions seems to be simpler and are more reliable.

2) Disable button / link on click.
The simplest client-side solution consists in writing this.disabled=true in onclick. An example:
 
<h:commandbutton action="..." onclick="this.disabled=true;" value="...">
 
I had kinda troubles with this solution and ajaxified buttons like PrimeFaces' p:commandButton - it didn't work. Furthermore the entire button gets frozen and doesn't respond anymore. We want to have a still responding button or link if user clicks on it multiple times.

3) Ajax queue and request delaying.
This is probably the best solution at all. Many popular component libraries already have this solution for the multiple clicks preventation. OpenFaces has e.g. a nice concept in order to avoid frequent requests. OpenFaces' Ajax framework sends only one request in case of several events during the short period of time specified with the "delay" attribute. RichFaces has a4j:queue and a4j:attachQueue. These components have an attribute "requestDelay". This attribute specifies the number of milliseconds to wait before sending a request in order to combine similar requests. The greater the value the fewer requests will be sent when fast typing. Similar requests in the queue are "combined" while waiting for the request delay. This feature results in just one request from a component being sent. For more details see RichFaces showcase and try to do double clicks to see they are "combined" to just one. Unfortunately, but PrimeFaces doesn't have similar feature what would prevent sending of miltiple requests from the same component like buttons / links, datatable filtering on keyup if user types very fast (important for large tables), etc.

4) Using jQuery's bind / unbind methods.
Ajax queue prevents double clicks, but doesn't ensure sending of slow multiple clicks. I have implemented my own solution for PrimeFaces' buttons / links. The idea is to bind onlick handler bind('click', function() {..}) and call unbind('click') within the handler :-) I have also tried jQuery .one() method but it didn't work as desired. We should prepare the renderer class at first. I have these lines there (only short outline for button renderer to get the idea):
writer.write(button.resolveWidgetVar() + 
    " = new PrimeFaces.widget.ExtendedCommandButton('" + clientId + "', {");
...
writer.write("});");
if (button.isPreventMultiplyClicks()) {
    writer.write(button.resolveWidgetVar() + ".bindOneClick('" + clientId + "', function(){" + onclick + "});");
}
ExtendedCommandButton is an extended widget based on the PrimeFaces' one. bindOneClick is a method in this widget and onclick is an onlick handler generated by PrimeFaces for Ajax / non Ajax requests. The extension looks as follows:
PrimeFaces.widget.ExtendedCommandButton = function(id, cfg) {
    PrimeFaces.widget.CommandButton(id, cfg);
}

jQuery.extend(PrimeFaces.widget.ExtendedCommandButton.prototype, PrimeFaces.widget.CommandButton.prototype);

PrimeFaces.widget.ExtendedCommandButton.prototype.bindOneClick = function(clientId, commandFunc) {
    var buttonEl = jQuery(PrimeFaces.escapeClientId(clientId));
    buttonEl.data('commandFunc', commandFunc);
    buttonEl.unbind('click');

    buttonEl.bind('click', function() {
        buttonEl.unbind('click');
        commandFunc();
    });
}
One problem still exists - if user stays on the same page (in case of Ajax updates) and the button is not updated, it doesn't respond more by reason of unbind. We should "reinitialize" it. Therefore I added this method too:
PrimeFaces.widget.ExtendedCommandButton.prototype.reinitialize = function(clientId) {
    var buttonEl = jQuery(PrimeFaces.escapeClientId(clientId));
    buttonEl.unbind('click');

    buttonEl.bind('click', function() {
        buttonEl.unbind('click');
        buttonEl.data('commandFunc')();
    });
}
So, if we navigate to another page (a non-Ajax request), we can write now:
 
<p:commandButton preventMultiplyClicks="true" ajax="false" ...>
 
If user stays on the same page (an Ajax request), a call PrimeFaces.widget.ExtendedCommandButton.reinitialize(clientId) is necessary in "oncomplete" to get multi-click preventation working again. Like this
 
<p:commandButton id="myButton" preventMultiplyClicks="true" ...
                oncomplete="PrimeFaces.widget.ExtendedCommandLink.reinitialize('myButton')">
 
Or you can try to include the button Id to the "update" attribute
 
<p:commandButton preventMultiplyClicks="true" update="@this,..." ...>
 
p:commandLink will be updated and reinitialized again. We can also extend the button renderer a little bit and reinitialize it automatically (if it's not in the Ajax update region). Result: the button / link will be a quite usually PrimeFaces' button / link with a new attribute for multiple clicks. No differences otherwise.
 
<p:commandLink "general PF attributes" preventMultiplyClicks="true">