Using PrimeFaces <p: ajax>, start Ajax in inputText only by pressing keys that change the field

I use PrimeFaces and has a p: inputText field where I need to update some components in the view based on the last keystroke inside p: inputText . Here is the code:

<p:inputText value="#{customerLController.surnameFilterConstraint}" id="surnamefilterfield"> <p:ajax event="keyup" update=":custForm:custDataTable" listener="#{customerLController.focusSurname}" oncomplete="primeFacesId('surnamefilterfield')"/> </p:inputText> 

The fact is that the above code launches Ajax even in the case of arrow key presses (which I would prefer to avoid an expensive update ). Ideally, I would like to use a different version of p: ajax event = "change" with the qualification that the change is pronounced on keystrokes, and not when the user presses Enter (what is happening now).

If the p: ajax component does not allow filtering out certain keyup events, then I understand that the only alternative (?) Would be to call client-side JavaScript and then implement the Ajax call in Javascript, but then I would refuse to use the PrimeFaces p: ajax component , is not it?

+5
source share
1 answer

Since JSF 2.2, I use an elegant way to solve this problem.

The solution is based on a combination of p:remoteCommand (as indicated in one of the comments) and a namespace http://xmlns.jcp.org/jsf/passthrough , which allows you to define your own HTML event attributes in JSF components.

In this case, it will be:

  • First add a new namespace to the page

     xmlns:pt="http://xmlns.jcp.org/jsf/passthrough" 
  • Change p:inputText and add p:remoteCommand

     <p:inputText id="surnamefilterfield" value="#{customerLController.surnameFilterConstraint}" pt:onkeyup="onKeyUpFilterKeyCode(event)"/> <p:remoteCommand delay="300" name="onFilteredKeyUp" actionListener="#{customerLController.focusSurname}" /> 
  • add javascript function

      function onKeyUpFilterKeyCode(event){ var keyCode=event.keyCode; console.log("Key code = " + keyCode); //if key is not ENTER and not cursor/arrow keys if ((keyCode != 13) && !((keyCode >= 37) && keyCode <= 40)){ //call remoteCommand onFilteredKeyUp(); } } 

(since this JS function contains "special" XML characters, follow BalusC 's recommendations on how to add it to a JSF / XML web page)

The advantage of this approach is that you can ajaxify any native HTML event supported by the component (and the WEB browser), while at the same time using the JSF / Primefaces components and the β€œJSF method” to create WEB pages.

0
source

All Articles