LStrike
LStrike

Reputation: 1648

Evaluate javascript result in jsf/primefaces component

I would like to know, how to make a connection between jsf/primefaces and javascript.

I want to call a listener in my backing bean after the user has typed a whitespace. To determine, which key was pressed, I got a javascript funktion

<script type="text/javascript">
   function displayunicode(e){
   var unicode=e.keyCode? e.keyCode : e.charCode
   return unicode
}
</script>

If "space" was pressed the value of 'unicode' is 32.

Now I to call this function from a primefaces component with a 'onkeyup event'

<h:form>
...

<p:inputTextarea id="inputBeschreibung" 
                                    value="#{bean.value}"
                                    rows="10" 
                                    cols="50"
                                    queryDelay="300" 
                                    maxlength="500"
                                    onkeyup="displayunicode(event); this.select()">

                    </p:inputTextarea> 

...
</h:form>

I wan't to something like this in my primefaces komponent:

if(displayunicode(event); == 32) callBacking bean Method.

I have no idea how to do this.

Upvotes: 1

Views: 685

Answers (1)

ppawel
ppawel

Reputation: 1056

From JavaScript to bean

To fire backing bean method from JavaScript you can use p:remoteCommand component: https://www.primefaces.org/showcase/ui/ajax/remoteCommand.xhtml

Here's the example from PrimeFaces user's guide:

<p:remoteCommand name="increment" actionListener="#{counter.increment}"
out="count" />

<h:outputText id="count" value="#{counter.count}" />

<script type="text/javascript">
    function customfunction() {
        increment(); //makes a remote call
    }
</script>

From bean to JavaScript

And if you want the opposite action you can use execute(...) method from org.primefaces.context.RequestContext class:

RequestContext context = RequestContext.getCurrentInstance();
context.execute("alert('hello from bean');");

Upvotes: 4

Related Questions