Sandra Sandra - 7 months ago 16
Javascript Question

How to process p:inputText change event

I am using p:inputText and my requirement is to fire a javascript function, that would update the backing bean searchField

<p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" />

<p:remoteCommand name="resetSearch" actionListener="#{searchBean.resetSearch}" process="@this" />


And here is my javascript function. I used firebug to find the id of inputText element and thats page:j_idt18:searchForm:j_idt20_input. Id is correct for sure

$("#page:j_idt18:searchForm:j_idt20_input").change(function() {
alert("Its here");
if(!this.value) {
resetSearch();
}
});


It looks fine to me, but when I edit my search field, by adding or deleting then alert is not fired. Main requirement is to call backing bean, when user uses backspace button to make the search field empty.

I checked id of inputText element and wrote a javascript function

My question is, how can I write javascript/jquery function, who constantly monitor any changes in the searchfield(p:inputText).

Answer

As per jquery selector Docs:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\.bar")

Hence, You need to escape special characters in ID

$("#page\\:j_idt18\\:searchForm\\:j_idt20_input").change(function() { 
  alert("Its here");
  if(!this.value) 
    resetSearch();
});

or use attribute equals selector to target element having special character in it:

$("[id='page:j_idt18:searchForm:j_idt20_input']").change(function() { 
  alert("Its here");
  if(!this.value)
     resetSearch();
});