Search code examples
ajaxjsflistenerkeyup

Conditional keyup listener on h:inputText?


I'm using JSF and I'd like to call a listener on an InputText element's keyup events, but only if the input text is longer than 3 chars.

My code is:

<h:inputText id="myId" styleClass="iceInpTxt uppercase" maxlength="15" 
value="#{controller.model.value}">
  <f:ajax event="keyup" listener="#{controller.listener}" render="anotherElement"/>
</h:inputText>

Now I'm checking the text's length in my listener, works perfectly but way to slowly. Is there a workaround, like a conditional listener, which is only called when inputText.length() > 3, in other cases the listener is ignored?


Solution

  • you can simply use a javascript-function that only returns true and hence triggers the listener if your required condition is matched.

    <h:inputText id="myId" 
    
       onkeyup="return checkLength(this)" 
    
       styleClass="iceInpTxt uppercase" maxlength="15" 
       value="#{controller.model.value}">
         <f:ajax event="keyup" listener="#{controller.listener}" render="anotherElement"/>
     </h:inputText>
    

    javascript:

    function checkLength(value){
       return value.length > 3;
    }