简体   繁体   中英

Call function from JSF backing bean with javascript var or other tag value

I' have seen many answers here but none worked for what I want, I need to do this in a way that the form is not submited, and by using the hidden button approach (with an ajax call) and calling the click() event from javascript, the method is called, but I need to pass an int in the method, how can I do that?

I can get the int from a javascript var or from a hidden input text field, just don't know how to do that, can anyone help with that?

JSF code:

<script type="text/javascript" language="javascript">
    var position;
</script>

<h:inputHidden id="hiddenHolder" value="#{backingBean.beanPosition}" />

<h:commandButton id="hiddenButton" style="display: none;">
    <f:ajax listener="#{backingBean.testMethod(need to send here javascript var or inputHidden value)}"/>
</h:commandButton>

Bean function;

public void testMethod(int i){
    //do stuff
}

When I change the hiddenHolder value from javascript that is not reflected in the backingBean, I guess it needs a submit for that to work. That is why I need to pass the value in the method call.

When I change the hiddenHolder value from javascript that is not reflected in the backingBean

You're indeed not telling JSF to process the input value. The <f:ajax execute> should be used for this, which defaults to @this (the current input or command component). As the <f:ajax> is enclosed inside a command component, only the command component itself (its action) will be processed.

So, just explicitly specify the input value along with the command component:

<f:ajax execute="@this hiddenHolder" ... />

Or, if this all is within the same form, use @form :

<f:ajax execute="@form" ... />

See also:

Use the OmniFaces commandScript for this. Works great (or use the PrimeFaces remoteCommand if you already use that)

To prevent the rest of the form being submitted, use the execute attribute like with an f:ajax call (process attribute on p:remoteCommand) or use separate forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM