Dynamator Pure HTML for every page generation technology.

Creating a Dynamically Populated Choice List

This example shows how to output the elements of an indexed property as a list of selection options, and how to show the currently selected option.



The first option in the list is hard-coded as blank. Because array references in Java are zero-based, the first option is indexed with value "-1". The second option in the list is marked with a class that will be used by Dynamator. The remaining options in each list are marked with class "Discard", which causes them to be removed by Dynamator.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <title>Favorite Color</title>
  Which color is your favorite?
  <select name="like">
    <option value="-1"></option>
    <option class="color">Red</option>
    <option class="Discard">Green</option>
    <option class="Discard">Blue</option>
  <input type="SUBMIT">

Dynamator File

<dynamator language="jsp">
    <%@ page session="false" %>
        private static final String[] colors_ = 
            new String[]
        String likeInput = request.getParameter("like");
        int like = 
            ( likeInput == null || likeInput.length() == 0 )
            ? -1
            : Integer.valueOf(likeInput).intValue();
  <class name="color">
    <foreach type="String[]" element="color" i="iColor">
    <attr name="value">
    <attr name="selected">
      <if>iColor == like</if>

In comparison with the previous example, the 'foreach' element has a new attribute, 'i'. The 'i' attribute names a variable to hold the iteration number, which in Java starts with 0.

The value sent by an option element in the HTTP request is the value of the 'value' attribute of the option element. Usually this is not the same as the text displayed by the option element; often, it is the offset or key of the indexed property whose name is displayed with the choice. In this example, the value is the value of the variable 'iColor'.

The '<content>' element near the end of the file causes the content of the option element to be dynamically set to the value of the variable 'color', which is the current element of the 'colors_' collection, as specified in the 'foreach' element.

JSP file

After processing with Dynamator, the resulting JSP file looks like this:

FavoriteColor.jsp (generated by Dynamator)

In Action

If you are viewing this page in a servlet engine, you can see the generated page in action.