I have the following problem:
In my data model I have a class called Type. Type consists of a title and a description.
Now I have a dropdown box in which the user may select an instance of Type:
<h:selectOneMenu id="typeDropdown" onchange="displayDescription();">
<f:selectItems value="#{operationCreator.types.title}" />
</h:selectOneMenu>
Below the dropdown box is a div area in which I want the description of the selected Type displayed.
My question is the following:
How can I store the description of the Type instances in javascript? A simple JSF tag which iterates over the list would do the job, but unfortunately I know of none. They all print additional HTML tags (like datatable), or work only with surrounding JSF tags (like selectItems).
I do know I could fix my problem using AJAX push, but I don’t want to. I want to access my data on page load in javascript.
I hope you can help me!
Thanks, Michael
Prepare the data in JSON format and let JSF just print it as a JS variable. You could do that either directly in backing bean
with
or in the view by iterating over a Java collection like
List<Type>and printing the JavaScript code accordingly if the values are guaranteed to not contain any special characters in JS such as quotes and newlines:The first way is preferable as it eliminates the risk for syntax errors in the produced JS code when the type title or description contains a JS special character. You can use among others Google Gson to convert a Java collection of beans to a string in valid JSON format.
Now, if you make sure that the item value of the dropdownlist is the type title, then you can get the associated description as follows
with