3.8. Dynamically Changing Select Options Using JavaScript

Problem

You want to use JavaScript to dynamically change the items displayed in an HTML select element based on data retrieved from your application's model.

Solution

Use the Struts logic:iterate tag to create JavaScript arrays for the different option sets. Then use a JavaScript onchange event handler to change the options set at runtime. Example 3-8 shows a complete JSP page where the JavaScript arrays are dynamically created using Struts tags. The changeOptions event handler function resets the options for the select control using the JavaScript arrays.

Example 3-8. Generating DHTML using Struts

<%@ 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" %> <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> <html> <head> <title>Struts - JavaScript Example</title> <script language="JavaScript"> // Create the array for the first set of options fooArray = new Array( ); <logic:iterate id="fooValue" indexId="ctr" name="MyForm" property="fooList"> fooArray[<bean:write name="ctr"/>] = new Option("<bean:write name='fooValue'/>", "<bean:write name='fooValue'/>", false, false); </logic:iterate> // Create the array for the second set of options barArray = new Array( ); <logic:iterate id="barValue" indexId="ctr" name="MyForm" property="barList"> fooArray[<bean:write name="ctr"/>] = new Option("<bean:write ...

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.