Populating Values dynamically in drop down boxes

ramani081399
ramani081399 used Ask the Experts™
on
I have a web application a JSP page that has two drop down boxes with following labels:
Drop down box 1: Choice1
                Choice2
                Choice3
                Choice4

Drop down box 2: ChoiceA
                ChoiceB
                ChoiceC
                ChoiceD


Currently I have hard coded these in the JSP page. I need to be able to do this more generically such that latter when more choices need to be added the user should not have the need to go and make changes in the JSP page but in some other external file from where these needs to be read and populeted in the two drop down boxes. How do i do this using server side implementation.

Also
When the page loads the above options appear in the drop down box.
But when, the user selects Choice1 from Drop down box 1, I want to be able to present the user with ChoiceA OR ChoiceB in the drop down box2. Similarly If the user selects Choice2 from the Drop down box 1, I need to be able to present ChoiceC OR ChoiceD.
How do i do this on the server side.A code to achieve both  would be appreciated.
Thanks
Ramani
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
it will be much easier if you have access to a database, you can store your choices into database table, and create choice relationship between box1 and box2.

of cause you can do it with filesystem files, but a may be a litter harder.

can you tell me in which way you want to go?

Author

Commented:
kennethxu,
    I would prefer the file system.
Thanks
Ramani
ok, let's say use an xml file:

<my-choice-file>
  <box1 choice="Choice1">
    <box2 choice="ChoiceA"/>
    <box2 choice="ChoiceB"/>
  </box1>
  <box1 choice="Choice2">
    <box2 choice="ChoiceC"/>
    <box2 choice="ChoiceD"/>
  </box1>
  ......  
</my-choice-file>

or

<my-choice-file>
  <choice id="1" desc="Choice1"/>
  <choice id="2" desc="Choice2"/>
  <choice id="3" desc="Choice3"/>
  <choice id="A" desc="ChoiceA"/>
  <choice id="B" desc="ChoiceB"/>
  <choice id="C" desc="ChoiceC"/>
  <choice id="D" desc="ChoiceD"/>
  <box1 choice="1">
    <box2 choice="A"/>
    <box2 choice="B"/>
  </box1>
  <box1 choice="2">
    <box2 choice="C"/>
    <box2 choice="D"/>
  </box1>
  ......  
</my-choice-file>

which one make more sense to you or you think it will be easier to maintain? actually, if you have long description and box2 items are been reused, 2nd is better, otherwise go for 1st.

let me know
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Author

Commented:
kennethxu,

   I think i would go with the first choice.
Ramani
ok,  once you have your xml file ready, you can use xml parser to read them into a map and store it as session or application attribute.

do you have experiece of parsing xml?

Author

Commented:
kennethxu,

   I know xml from a very theoretical point, but havent implemented parsing. I would appreciate if you can show the code for doing the parsing and and dsiplaying the way i decribed in a jsp page.
Ramani
here is a sample code to process the xml file into a Map, it is a excutable class, but you can also used it in your jsp:

import javax.xml.parsers.*;
import org.xml.sax.*;
import java.util.*;

public class MyOptions extends org.xml.sax.helpers.DefaultHandler {

     private Map options= new HashMap();
     private List suboptions = null;

     public MyOptions()
          throws ParserConfigurationException, SAXException, java.io.IOException
     {
          SAXParserFactory factory = SAXParserFactory.newInstance();
          SAXParser parser = factory.newSAXParser();
          parser.parse( new java.io.File("myoptions.xml"), this );
     }

     public Map getOptions() {
          return options;
     }

     public void startElement(String uri, String localName, String qName, Attributes attrs) {
          if(qName.equals("box1")){
               suboptions = new ArrayList();
               options.put( attrs.getValue( "choice" ), suboptions );
          } else if( qName.equals("box2") ) {
               suboptions.add( attrs.getValue( "choice" ) );
          }
     }


     public static void main( String[] args ) throws Exception
     {

          Map options = new MyOptions().getOptions();
          Iterator box1 = options.keySet().iterator();
          while( box1.hasNext() ) {
               String option = (String) box1.next();
               System.out.println( option );
               Iterator box2 = ((List)options.get(option)).iterator();
               while( box2.hasNext() ) {
                    System.out.println( "-" + box2.next() );
               }
          }
     }

}

let me know if you have question on how to get above work.

Author

Commented:
kennethxu,

   So, the class MyOptions would be a javabean?? How do i use this in the jsp page?? Normally we would do a bean.get() Or bean.write. I am not sure how to use this in the jsp page. Appreciate your help.
Thanks
ramani
it is a javabean, it is also executable so you can test like java MyOptions, it will print out the option list.

I have already provide getOptions method, you can add more get or write method when you see a need.

in you jsp page, you get the current selection of box1 as:
String selected = request.getParameter( "box1" );

you can get all box1 options from
Iterator box1 = options.keySet().iterator();

and related box2 options from:
Iterator box2 = ((List)options.get(selected)).iterator();

see example code in main method about how to use Iterator.

Author

Commented:
kennethxu,

   The java class compiles and dsiplays the values to the console. Itried running this by pullingthe values into the Jsp page but seems not to get it working corectly
I am sending what i wrote.

<%@ page contentType="text/xml" %>
<%@ page import="MyOptions.*" %>

<jsp:useBean id="dropdownoptions"
class="dropdownoptions.MyOptions" />
<%
Map options= new HashMap();
options = dropdownoptions.getOptions();
Enumeration enu1 = options.keys();
Object obj = null;
%>

<% while (enu1.hasNext()) { %>
<% obj = enu1.nextElement();%>
<%Iterator box2 = ((List)options.get(selected)).iterator();%>

<tr>
   
   <td>View </td>
      <td>Type</td>
       <td>
        <select>
                   
         <option>obj</option>
         </select>
         </td>
     </tr>
     <tr>
     <td>Category</td>
     <td>
        <select>
                   
         <option>box2</option>
         </select>
         </td>
     </tr>
<% } %>


Tell me if this is the way to display all the optioons in the top drop down and based on the selections in the drop down the relevant drop downs appear in the box below the first one.

Thanks
Ramani

Author

Commented:
kennethxu,
Sorry I changed the JSP , but i dont get the output with only two drop down boxes
<%@ page contentType="text/xml" %>
<%@ page import="ThirdJSP.MyOptions" %>

<jsp:useBean id="dropdownoptions" scope="page"
          class="ThirdJSP.MyOptions" />
<%
Map options= new HashMap();
options = dropdownoptions.getOptions();
Iterator box1 = options.keySet().iterator();

%>
<% while (box1.hasNext() ) { %>
<%String selected = (String) box1.next();%>

<tr>
   
   <td>View </td>
      <td>Type</td>
       <td>
        <select>
                   
         <option><%= selected %></option>
         </select>
         </td>
     </tr>

<%Iterator box2 = ((List)options.get(selected)).iterator();%>

 <%while( box2.hasNext() ) {%>
     <tr>
     <td>Category</td>
     <td>
        <select>
                   
         <option><%= box2 %></option>
         </select>
         </td>
     </tr>
<%}%><%}%>


Ramani
not good coding style, but this test code works for me and it demos what you need to do. please notice that i don't put the bean into use, instead I hardcode the data, you'll have to chage something in order to get it work with you bean.

<%@ page import="java.util.*" %>
<%
    Map opts = new HashMap();
    String[] sub;
    opts.put( "Choice1", new String[]{ "ChoiceA", "ChoiceB" } );
    opts.put( "Choice2", new String[]{ "ChoiceC", "ChoiceD" } );
%>
<script language="JavaScript">
<!--
function update() {
 var action = null;

    for (i=0;i<form1.box1.length;i++) {
       if (form1.box1.options[i].selected) {
          action = "?box1="+form1.box1.options[i].text;
       }
    }
 location.replace(action);
}
// -->
</script>


<form name="form1">

box1:<p>
<select name="box1" onchange="javascript:update()">
<%
    String sel = request.getParameter( "box1" );
    if( sel == null ) sel = "Choice1"; //default choice

     Iterator box1 = opts.keySet().iterator();
     while( box1.hasNext() ) {
           String option = (String) box1.next();
%>
<option <%=option.equals(sel)?"selected":""%>><%=option%></option>
<%
        }
%>
</select><p>

box2:<p>
<select name="box2">
<%
    String[] box2 = (String[])opts.get(sel);
    for( int ii = 0; ii < box2.length; ii++ ) {
%>
       <option><%=box2[ii]%></option>
<%  } %>
</select>

</form>

Author

Commented:
kennethxu,
  I tried using the bean and the code u suggested. The JSP page loads with two drop down boxes. But when change my choice to in the second drop down i get error saying
Only one top level element is allowed in an XML document. Line 22, Position 2
 

<form name="form1">
-^


<%@ page import="java.util.*" %>
<%@ page contentType="text/xml" %>
<%@ page import="ThirdJSP.MyOptions" %>
<jsp:useBean id="dropdownoptions" scope="page"
         class="ThirdJSP.MyOptions" />
<%
Map options= new HashMap();
options = dropdownoptions.getOptions();
Iterator box1 = options.keySet().iterator();

   
%>
<script language="JavaScript">
<!--
function update() {
var action = null;

   for (i=0;i<form1.box1.length;i++) {
      if (form1.box1.options[i].selected) {
         action = "?box1="+form1.box1.options[i].text;
      }
   }
location.replace(action);
}
// -->
</script>


<form name="form1">

box1:<p>
<select name="box1" onchange="javascript:update()">
<%
   String sel = request.getParameter( "box1" );
   if( sel == null ) sel = "Choice1"; //default choice

   
    while( box1.hasNext() ) {
          String option = (String) box1.next();
%>
<option <%=option.equals(sel)?"selected":""%>><%=option%></option>
<%
       }
%>
</select><p>

box2:<p>
<select name="box2">
<%
   Iterator box2 = ((List)options.get(sel)).iterator();
  while(box2.hasNext()) {
 
%>
      <option><%=box2.next()%></option>
<%  } %>
</select>

</form>
should be:
<%@ page contentType="text/html" %>

better to be:

Map options= dropdownoptions.getOptions();

you might want to use "application" or "session" scope for your bean if you need better performance

Author

Commented:
I changed the page type to be text/html and still i get the error Only one top level element is allowed in an XML document. Line 34, Position 2
 

<form name="form1">

Why is this.

Ramani

Author

Commented:
Now the jsp page displays the two drop downs. But in the first drop down if i select choice1 it goes back to choice2 and does not show the corresponding ones in the second box
Ramani


<%@ page import="java.util.*"%>
<%@ page contentType="text/html"%>
<%@ page import="ThirdJSP.MyOptions"%>
<jsp:useBean id="dropdownoptions" scope="page"
         class="ThirdJSP.MyOptions" />




<script language="JavaScript">
<!--
function update() {
var action = null;


   for (i=0;i<form1.box1.length;i++) {
      if (form1.box1.options[i].selected) {
         action = "?box1="+form1.box1.options[i].text;
      }
   }
location.replace(action);
}
 //-->
</script>




<%
Map options= new HashMap();
options = dropdownoptions.getOptions();
Iterator box1 = options.keySet().iterator();
%>
   




<form name="form1">

box1:<p></p>
<select name="box1" onchange="javascript:update()">
<%
   String sel = request.getParameter( "box1" );
   if( sel == null ) sel = "Choice1"; //default choice

   
    while( box1.hasNext() ) {
          String option = (String) box1.next();
%>
<option> <%=option%></option>
<%
       }
%>
</select><p></p>

box2:<p></p>
<select name="box2">
<%
   

  Iterator box2 = ((List)options.get(sel)).iterator();
 while(box2.hasNext()) {
 
%>
      <option><%=(String)box2.next()%></option>
<%  } %>
</select>

</form>

try to close you browser and re-open.

also, to be complete:

<%@ page import="java.util.*"%>
<%@ page contentType="text/html"%>
<%@ page import="ThirdJSP.MyOptions"%>
<jsp:useBean id="dropdownoptions" scope="page"
        class="ThirdJSP.MyOptions" />
<html>
<head>
<title>My Option Test</title>

<script language="JavaScript">
<!--
function update() {
var action = null;


  for (i=0;i<form1.box1.length;i++) {
     if (form1.box1.options[i].selected) {
        action = "?box1="+form1.box1.options[i].text;
     }
  }
location.replace(action);
}
//-->
</script>

</head>
<body>

<%
Map options = dropdownoptions.getOptions();
Iterator box1 = options.keySet().iterator();
%>
 

//rest of you code here

</body>
</html>

Author

Commented:
kennethxu,
Thanks
Ramani

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial