Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsf calling bean method from input text when pressing enter

Tags:

jsf

primefaces

JSF 2.0, Mojarra 2.0.1, PrimeFaces 3.4.1

Here is a p:inputText component which is expected to call a backing bean method when the enter key is pressed.

<p:inputText id="commentInput" rendered="#{status.haveComment}" 
    value="#{statusBean.newComment}"
    onkeypress="if (event.keyCode == 13) { onchange(); return false; }">
    <f:ajax event="change" listener="#{statusBean.test}" />
</p:inputText>

While backing bean has the method of:

public void test(AjaxBehaviorEvent event) {
   System.out.println("Pressed enter!");
}

It's calling method when enter key is pressed but it has more than this; unexpected behaviour case:

--Click input text
----Type some letters
------Click somewhere else in the page
--------CONSOLE: Pressed enter!

I think ajax event=change detects a change somehow and calls the method. How to convert this p:inputText component into a proper comment taker component like Facebook or others has?

like image 334
Ömer Faruk Almalı Avatar asked Feb 19 '13 14:02

Ömer Faruk Almalı


2 Answers

This is the way how onchange event works in HTML. It is happening when text in input element is changed, but is fired when component loses focus (in your case that is the moment when you click somewhere else in the page).

You can define p:remoteCommand for test method and just write:

<p:remoteCommand name="test" actionListener="#{statusBean.test}"/>
<p:inputText id="commentInput" rendered="#{status.haveComment}" 
  value="#{statusBean.newComment}"
  onkeypress="if (event.keyCode == 13) { test(); return false; }"/>

and in backing bean:

public void test() {
 System.out.println("Pressed enter!");
}
like image 192
partlov Avatar answered Nov 14 '22 01:11

partlov


With newer PrimeFaces versions (5+ at least) you can use p:defaultCommand instead of scripting. Though you can't use p:remoteCommand then, because p:defaultCommand needs something clickable.

<p:inputText id="input" />
<p:defaultCommand target="submit" />
<!--you can show the button to allow the user to click too, or hide it with display: none-->
<p:commandButton id="submit" style="display: none;" process="input" />

By default p:defaultCommand applies to the whole form. You could limit it with the scope attribute.

like image 24
Vsevolod Golovanov Avatar answered Nov 14 '22 01:11

Vsevolod Golovanov