File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JSF and the fly likes Passing JSF values in a JavaScript on load function Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » JSF
Bookmark "Passing JSF values in a JavaScript on load function" Watch "Passing JSF values in a JavaScript on load function" New topic

Passing JSF values in a JavaScript on load function

Wally Hartshorn
Ranch Hand

Joined: Jan 30, 2003
Posts: 77
Okay, I'm feeling sort of stupid because I can't figure this out. It seems like there must be a simple solution, but I'm just too dense to see it!

I have a JSF page (using MyFaces and Tomahawk). When that page loads, I have some JavaScript that immediately runs and does some stuff. While I was mocking it up, I had code like this:

It worked fine, but I didn't want to hard-code the "3, 4, 15" in there. Instead, I wanted my Java bean to supply the values, which the JavaScript method would then use.

My first attempt was this:

Alas, that doesn't work, which isn't too surprising since the BODY tag is not a JSF tag.

Okay... So what WILL work?

The only thought I have is to have 3 hidden fields, which the JavaScript then access to get the values. It feels sort of icky, however, so I figured I would check to see whether there's a more elegant way to pass values from JSF to a JavaScript on load function.

Any ideas?

Wally Hartshorn
Sergey Smirnov
Ranch Hand

Joined: May 29, 2003
Posts: 167
If you use Facelets with MyFaces, the code you mentioned should work as is. Probably, it is even better to use immediate notation such as ${myBean.thing1}.

If you do not use facelets, the solution might not look so trivial.
You can use outputText tag inside the javascript code. Like:

It looks ugly, but it is a shortest way if you container does not support Servlet 2.4 specification. If it does, you can try ${} instead of #{} (Some restrictions might apply)
Using scriptlets also is an option, but it looks even more ugly.
[ September 18, 2006: Message edited by: Sergey Smirnov ]
I agree. Here's the link:
subject: Passing JSF values in a JavaScript on load function
It's not a secret anymore!