Thursday, May 31, 2012

Control the keyboard tab behavior in a LOV field

The keyboard tabbing behavior of list of value fields in ADF Faces is such that the focus is set to the LOV icon when navigating out of the input field.
While this behavior is convenient for those who frequently use List of Values, it’s a bit annoying to users who prefer to type ahead and either click onto the LOV icon or use a keyboard shortcut to launch the select dialog if needed.

In the following, I explain how to change the default LOV behavior in ADF Faces with a little JavaScript. The modified behavior will set the focus to the next input field when the tab keyboard key is pressed. To launch the list of values dialog, users press the F2 key.
The JavaScript is added to the page using the af:resource tag. Note that while the JavaScript code in the sample is added in the tag body, in real life it should be referenced from an external file.
          function tabOutOfLOVField(evt) {
              keyCode = evt.getKeyCode();
              if (keyCode == AdfKeyStroke.TAB_KEY) {
                  var lovField = evt.getSource();
                  nextComponent = evt.getSource().getProperty("nextComponent");
                  var nextField = lovField.findComponent(nextComponent);
                  nextField.focus();
                  evt.cancel();
              }
              else if (keyCode == AdfKeyStroke.F2_KEY) {
                  var lovField = evt.getSource();
                  AdfLaunchPopupEvent.queue(lovField, true);
                  evt.cancel();
              }
          }
The JavaScript code first determines the keyboard key a user pressed. If the key is the TAB key then the list of value field is referenced from the event object. The next navigation target, the input field to add focus to next, is found by a relative search using the input text ID property value. If the user pressed key is F2 then the list of value field is queued for its popup launch event so the LOV dialog opens. In both cases, as there is no more to do for ADF Faces on the server side, the event is cancelled, to suppress server propagation of the keyboard action.
To execute the JavaScript code, an af:clientListener and af:clientAttribute tags are added to the af:inputListOfValues component as shown below:


The client listener tag added to the input component listens for the keyboard down event and calls the JavaScript function explained earlier.The client attribute sets the id of the next component selected after keyboard down event.
You can download this sample from the link below: (it uses the FOD demo schema which you can find it here)