0

Can you please help me out in doing this? I am trying to get value from backing bean in my javascript on click of the command button.

this is my jsf command button

   <h:commandButton id="me" value="test" action="#{ques.conversiontostring}"
         onclick="mystring()"/>

this my javascript function

   function mystring()
    {
    var mystring = window.document.getElementById("form:me").click(); 
    alert(mystring);

    }

my bean returns a string that i am storing in mystring variable, but when i alert i get null value. that would be great if someone helps in doing that. Thanks in advance.

2 Answers 2

1

You mean something like this?

<h:commandButton id="me" value="test" action="#{ques.conversiontostring}"
     onclick="myFunction('#{ques.mystring}')"/>

function myFunction(message)
{
  alert(message);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@user1101422 Make sure apostrophes are present around EL expression passed as function argument.
1

I understand that you want so show a string value which is been set by the action method? You can only show it once it has been completed. You need to realize that JSF and JS does not run in sync as you'd expect from the coding. JSF is basically a HTML code generator. JS only works on the current HTML DOM tree. You need to let JSF generate HTML code in such way that the JS code get executed once the HTML response arrives at the webbrowser.

Assuming that you have this JS:

function show(string) {
    alert(string);
}

And assuming that you have this bean:

private String message;

public void show() {
    message = "Hello!";
}

public String getMessage() {
    return message;
}

If you're using JSF 1.x, use the following approach:

<h:commandButton value="show" action="#{bean.show}" />
<h:panelGroup rendered="#{not empty bean.message}">
    <script>show('#{bean.message}');</script>
</h:panelGroup>

If you're using JSF 2.x which supports ajax, you could alternatively use the following approach:

<h:commandButton value="show" action="#{bean.show}">
    <f:ajax render="message" />
</h:commandButton>
<h:panelGroup id="message">
    <h:panelGroup rendered="#{not empty bean.message}">
        <script>show('#{bean.message}');</script>
    </h:panelGroup>
</h:panelGroup>

3 Comments

I can't get the above solution to work in JSF 2.2 :(
@fuzzyanalysis: JSF 2.x solution works for me on JSF 2.2 too.
Thanks BalusC. I got your solution working after all. It's just a matter of getting the order of events in which javascript <script> blocks work with Primefaces components correct, as you mentioned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.