Search code examples
javascriptformsjsfmanaged-beancommandbutton

How to pass bean value to JavaScript before form submit


I am making webpage about ride sharing/selling bus tickets using JSF.
On one particular page, logged users can publish their ad (offering or looking for ride).
They should enter info like: ad title, origin city, destination city, departure time, etc.

What I want is, that users get weather forecast of destination city showed in popup after they hit submit.
This also means I am consuming service like openweathermap.

Basically, I have one h:form and h:commandButton like this:

<h:commandButton value="Publish" action="#{adBean.publishAd}" type="submit" onclick="showPopup()">
</h:commandButton>

The problem is that I don't know how to pass bean value of

<h:inputText value="#{adBean.ad.destinationCity}"/>

to JavaScript method showPopup().

I've tried this, but destinationCity turns out to be null.

<h:commandButton value="Publish" action="#{adBean.publishAd}" type="submit" onclick="showPopup(#{adBean.ad.destinationCity})">
</h:commandButton>

Why is this happening and how can I pass its value to JavaScript code?


Solution

  • It is null because it is put in an attribute (onclick) that is used for javascript. Attributes like these are 'rendered' at the time the page is displayed, not (again) at submission time or other moments. So if it is initialized null at that time, what is transferred from the server to the client is

    <button value="Publish" ... onclick="showPopup(null)" />
    

    A quote from @BalusC about this in How to invoke a bean action method using a link? The onclick does not work:

    In JSF, only the attributes which interpret the EL expression as a MethodExpression can be used to declare action methods. All other attributes are interpreted as ValueExpression and they are immediately executed when the HTML output is generated by JSF. This covers the onclick attribute, whose value should actually represent a JavaScript function.

    The (h:?)inputText on the client-side is rendered as a plain html inputText, so if you want access to its value before submitting (like I suspect you want to), you can do so in the showPopup like you would in plain html/javascript.

    How to do this is mentioned in many stackoverflow Q/A so either pick one that suites you best e.g. How do I get the value of text input field using JavaScript?, but make sure to also read How can I know the id of a JSF component so I can use in Javascript