Passing JS variable to Managedbean

Asked

Viewed 603 times

0

I have a variable in js, and I need to send it to my Managedbean, which is the most correct way to do this?

1 answer

1

You can manipulate the DOM to do what you need, follow an example:

<h:form id="formId">
    <h:inputHidden id="x" value="#{bean.x}" />
    <h:inputHidden id="y" value="#{bean.y}" />
    <h:commandButton value="submit" onclick="getVars()" action="#{bean.method}" />
</h:form>

Your Javascript function:

   function getVars() {
       // ...
       var x = 10; 
       var y = 20;

       document.getElementById("formId:x").value = x;
       document.getElementById("formId:y").value = y;
    }

In your bean:

private int x; 
private int y; 
public void method() {
    System.out.println("x: " + x); 
    System.out.println("y: " + y); 
// ... 
}
  • I tried this way. <h:inputHidden id="idBancoPai" value="#{footsMBean.idBancoPai}" /> But when I try to get it in the bean, the value comes to 0. Don’t take the actual value selected. You know what it can be?

  • Without seeing your codes, I wouldn’t be able to answer you. But try to see if the bean method is being invoked before going through javascript. I already did that (manipulate DOM via JS and send to Bean) and had no problems.

  • When Voce says, if the bean method is being invoked before going through javascript? would that be more or less what? Because at first what I need is, I click on the corresponding line, select the id I need, then step into the input, and take the bean

  • Place a breakpoint on your JS and Bean, see if clicking the button (or anything else) that triggers the action follows the order (1st javascript, 2nd bean).

  • 1

    I got Marcos, the problem was pretty silly, I had put the <h:inputHidden id="idBancoPai" value="#{bancoPergusMBean.idBancoPai}" /> in another form that is on the same page, with this every time I submitted the form to get it in the bean the value zeroed. Thanks for the help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.