3.9. Generating Dynamic Select List Options

Problem

You want to dynamically change the options displayed in a select element based on a change in another field in the same form, without having to render the set of options in client-side JavaScript.

Tip

This problem isn't about avoiding JavaScript altogether; instead, it shows how to call a Struts action from a client-side JavaScript event listener.

Solution

Use an onchange or onclick JavaScript listener to call a JavaScript function that submits the form to a Struts Action. In the Action, perform the necessary business logic to construct a new collection for the select options, and forward control back to the original JSP page. Example 3-11 shows a JSP page that submits the form to an Action when the user clicks a radio button. The value of the radio button is passed to the Action as a request parameter.

Example 3-11. Submitting a form using JavaScript

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <html> <head> <title>Struts - JavaScript Example</title> <script language="JavaScript"> function getOptions(control) { form = control.form; form.action = "SetOptions.do?someProp="; form.action += control.value; form.submit( ); } </script> </head> <body> <html:form action="ProcessMyForm"> <html:radio property="someProp1" value="val1" onclick="getOptions(this);"/> Value 1<br/> <html:radio property="language" ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.