Search code examples
jqueryjspservletsstruts

Dynamic DropDown List in JSP without Using AJAX


I want to display multiple dropdowns on a JSP page. I am using Struts and get the following data object in my JSP page.

<%
Map<String, CustomObject> data = (Map<String, CustomObject>)renderRequest.getAttribute("data");%>

The first list (call it A) displays all the keys from the data and is defined as following.

<select id="A" name="A" onchange="?">
    <option value="">Please Select</option>
    <c:forEach var="entry" items="${data}">
        <option value="${entry.key}">${entry.key}</option>
    </c:forEach>
</select>

I am not sure how I should define the remaining lists but what I want is that based on selection in A, the remaining three dropdowns should be populated dynamically using the CustomObject corresponding to A (values in A are key in data). The CustomObject class is defined as following

class CustomObject{
    List<String> b;
    List<String> c;
    List<String> d;
}

I do not want to use Ajax since all the data required is already present in the Map. Any idea how could I achieve this.

Thanks


Solution

  • The solution that I found is to declare three global javascript variable and initialize them to values for each child dropdown using the Map passed in request e.g

    var dataB = { <c:forEach items="${data}" var="item" varStatus="loop">  
        "${item.key}" : [ <c:forEach items="${item.value.list}" var="value"
                    varStatus="subLoop"> "${value}" ${not subLoop.last ? ',':''
                  </c:forEach> ]
         ${not loop.last ? ',' : ''}
         </c:forEach> };
    

    Then have a method that is called onChange of Dropdown A and populates the dropdowns with the values corresponding to selection in DropDown A.

    I am not sure how elegant the solution is but it works.