Link to home
Start Free TrialLog in
Avatar of keneticintrouble
keneticintrouble

asked on

How to create a combo box in jsp???

Hi, i'm having trouble creating a combo box in jsp. For example if you select a value from dropdown menu 1, dropdown menu 2 will display a corresponding value from dropdown menu 1. if i select the vallue: Breakfast in the first menu, in the second menu, i should be able to choose what i can have for breakfast, such as hotdog, hotcakes, cereal etc...... if i select the vallue: Lunch in the first menu, in the second menu, i should be able to choose what i can have for lunch, such as rice, noodles, vegatables, meat etc......
I hope you can grasp the concept correctly...... i would like to retreive values from mysql database.

this is what i've started with..... i hope that you can give me some idea on how to continue with it.... would javascript be required in this process too?

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<p>
<!-- Open connection and execute query -->
<%
Class.forName("org.gjt.mm.mysql.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("Select * from meal");
%>
 
<!-- start to populate the table -->
<select name="test">
<%
while (rs.next()){
String type = rs.getString("type"); // the type of meal, whether it is breakfast or lunch

%>
<option value= "<%= type%>"><%= type%></option>
<% } %>
</select>

<% ResultSet rs2 = statement.executeQuery("Select * from meal"); %>
<select name="test2">
<%
while (rs2.next()){
String items= rs2.getString("items"); // the food items that i can choose from either breakfast or lunch meals

%>
<option value= "<%= items%>"><%= items%></option>
<% } %>
</select>


<!-- Close the connection -->
<%
statement.close();
connection.close();
%>


</body>
</html>



Thanks for your time!
Avatar of Karaa
Karaa

<%
String typefood;////////// give dynamic value to your combobox as <%=typefood%>

     rset = stmt.executeQuery(str);

%>
<select name="type_of_food" id="<%=typefood%>"style="width:140px;">
<%
    while (rset.next())
    {
    String      type = rs.getString("type"); %>
<option value="<%=type%>" <%=((type.toString().equals(typefood))?"SELECTED":"")%>><%=type%></option><%
}
%>
</select>
<%
Idea is straight forward that in the data base you have to enter one field for each field whether it is for breakfast, lunch or dinner and when first popup is selected,take selected value and prepare sql statement with a
select * from meal where type is like 'lunch"
you have to use onChange event of combox which actually submits your page and on Load of the same page you will have this SQL search which will use your "type" variable give u output
correction::>>>>>one field for each "type" whether it is for breakfast, lunch or dinner  
hello keneticintrouble,

I think is better to do that in javascript, build javascript object  with differrent possible values, and change combo 2 content dynamicly. Otherwise, each time the user change selection in combo1 you make a request and a response to the client, the user still not submit your form or send data. There also a refresh of the page each time he changes combo 1 selection.

regards
For Javascript
u can use
<script language="JavaScript">
<!--
function getSelected( selectbox ) {
 for (i=0;i<selectbox.length;i++)
    if (selectbox.options[i].selected) return selectbox.options[i];
}

function update( level ) {
  var action = "?box1="+getSelected(form1.box1).text;
  if( level >= 2 ) action += "&box2="+getSelected(form1.box2).text;
  location.replace(action);
}
// -->
</script>

where as  form1 ,box1 &nd box2 are
<form name="form1">
<select name="box1" onchange="javascript:update(1)">
<select name="box2" onchange="javascript:update(2)">
on load u populate box1 and box2 as u were doing

Avatar of keneticintrouble

ASKER

To Karaa:
Could you type out the javascript code for me to see properly because i can't understand your existing code. I can only see one select box..... I need two so that the first one will show the type of the food: breakfast, lunch or dinner and then only after the first select box has been selected, the second select box will display the corresponding value, which are the items: if breakfast is selected, the items will be bread, jam and hotcakes. If lunch is selected, the items will be beef, chicken and rice etc.....

When i viewed the javascript code, it couldn't run as expected. There was an error in the page.

Also, what do you mean by the on load???

Greatly appreciated your time on this
Try to get some idea from these two examples

<HTML>
<HEAD>
<TITLE>Dynamic SELECTs</title>
<SCRIPT language='JavaScript'>
<!-- //

// create js arrays to hold the data for selCity

var aryCityData = new Array();

aryCityData[0] = new Array();
aryCityData[0][0] = new Option('Select a State','0');

aryCityData[1] = new Array();
aryCityData[1][0] = new Option('Los Angeles','301');
aryCityData[1][1] = new Option('Oakland','304');
aryCityData[1][2] = new Option('Rio Linde','305');
aryCityData[1][3] = new Option('San Diego','302');
aryCityData[1][4] = new Option('San Fransisco','303');

aryCityData[2] = new Array();
aryCityData[2][0] = new Option('Miami','101');
aryCityData[2][1] = new Option('Orlando','102');
aryCityData[2][2] = new Option('Tampa','103');

aryCityData[3] = new Array();
aryCityData[3][0] = new Option('Abilene','201');
aryCityData[3][1] = new Option('Austin','202');
aryCityData[3][2] = new Option('Dallas','203');
aryCityData[3][3] = new Option('Houston','204');


function reloadCities(curStateIndex)  // pass in the current State index
{
  if ( curStateIndex < 0 ) return;  // no state selected, so do nothing

  var aryCityOpts = document.myform.selCity.options;  // points to selCity options array

  aryCityOpts.length=0;  // first, clear the current City options ...

  // then re-load the City options with values for the current State
  for ( var i=0,n=aryCityData[curStateIndex].length; i<n; i++ )
  {
     //// the line below no longer works in IE5 (it works in IE4 and NS4+).
     // aryCityOpts[aryCityOpts.length-1] = new Option(aryCityData[curStateIndex][i].text,aryCityData[curStateIndex][i].value);
     //// therefore, it now takes three lines to do the same thing:

     aryCityOpts.length++;  // add a new Option, then put data in it (below)
     aryCityOpts[aryCityOpts.length-1].text  = aryCityData[curStateIndex][i].text;
     aryCityOpts[aryCityOpts.length-1].value = aryCityData[curStateIndex][i].value;
  }
}

// -->
</script>

</head>

<BODY onLoad='document.myform.selState.focus();'>
<FORM name='myform' method='post' action='whatever.asp' onSubmit='return(false);'>

 State: &nbsp;
 <SELECT name='selState' size='1' onChange='reloadCities(this.selectedIndex);'>
   <OPTION value='0'></option>
   <OPTION value='30'>California</option>
   <OPTION value='10'>Florida</option>
   <OPTION value='20'>Texas</option>
 </select><P>

 City: &nbsp; &nbsp;
 <SELECT name='selCity' size='1' onChange='alert(this.options[this.selectedIndex].value)'>
   <OPTION value=''>Select a State</option>
   <OPTION></option>
   <OPTION></option>
   <OPTION></option>
 </select><P>

</form>
</body>
</html>

Example2

<%@ page import="java.util.*, java.sql.*" %>
<%!
private static String sqlBox1 = "select supplier from suppliers";
private static String sqlBox2 = "select depot from depots where supplier = ?";
private static String sqlBox3 = "select part from static_data where supplier = ? and depot = ?";
private static String sqlBox4 = "select family_name from families where supplier = ? and part = ?";
%>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = null;
Statement stat = null;
PreparedStatement ps = null;
try {

con = DriverManager.getConnection("jdbc:odbc:testdb");
stat = con.createStatement();
ResultSet rs = null;
%>
<html>
<head>
<script language="JavaScript">
<!--
function getSelected( selectbox ) {
 for (i=0;i<selectbox.length;i++)
    if (selectbox.options[i].selected) return selectbox.options[i];
}

function update( level ) {
  var action = "?box1="+getSelected(form1.box1).text;
  if( level >= 2 ) action += "&box2="+getSelected(form1.box2).text;
  if( level >= 3 ) action += "&box3="+getSelected(form1.box3).text;
  location.replace(action);
}
// -->
</script>
</head>
<body>

<form name="form1">

box1:<p>
<select name="box1" onchange="javascript:update(1)">
<%
 String sel1 = request.getParameter( "box1" );

 rs = stat.executeQuery( sqlBox1 );
 while( rs.next() ) {
      String option = rs.getString(1);
       if( sel1 == null ) sel1 = option; //make first as default choice
%>
<option <%=option.equals(sel1)?"selected":""%>><%=option%></option>
<%
  }
  rs.close();
%>
</select><p>

box2:<p>
<select name="box2" onchange="javascript:update(2)">
<%
  String sel2 = request.getParameter( "box2" );

  ps = con.prepareStatement( sqlBox2 );
  ps.setString( 1, sel1 );
  rs  = ps.executeQuery();
 while( rs.next() ) {
      String option = rs.getString(1);
       if( sel2 == null ) sel2 = option; //make first as default choice
%>
    <option <%=option.equals(sel1)?"selected":""%>><%=option%></option>
<%  }
 rs.close();
  ps.close();
%>
</select><p></p>

box3:<p>
<select name="box3" onchange="javascript:update(3)">
<%
 String sel3 = request.getParameter( "box3" );

  ps = con.prepareStatement( sqlBox3 );
  ps.setString( 1, sel1 );
  ps.setString( 2, sel2 );
  rs  = ps.executeQuery();
 while( rs.next() ) {
      String option = rs.getString(1);
       if( sel3 == null ) sel3 = option; //make first as default choice
%>
    <option <%=option.equals(sel2)?"selected":""%>><%=option%></option>
<%  }
 rs.close();
  ps.close();
%>
</select><p></p>

box4:<p>
<select name="box4" >
<%

 String sel4 = request.getParameter( "box4" );

  ps = con.prepareStatement( sqlBox4 );
  ps.setString( 1, sel1 );
  ps.setString( 2, sel3 );
  rs  = ps.executeQuery();
 while( rs.next() ) {
      String option = rs.getString(1);
       if( sel4 == null ) sel4 = option; //make first as default choice
%>
    <option ><%=option%></option>
<%  }
 rs.close();
  ps.close();
%>
</select>

<%
} finally {
  if( stat != null ) try { stat.close(); } catch( Exception e ) {}
  if( ps != null ) try { ps.close(); } catch( Exception e ) {}
  if( con != null ) try { con.close(); } catch( Exception e ) {}
}
%>

</form>
</body>
</html>

These are examples already posted on this forum
ASKER CERTIFIED SOLUTION
Avatar of kokchoon78
kokchoon78

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
kokchoon78's comment helped greatly. It provided me the basis and concept of how it shd be done..... it is the complete working code..... 2 pages worths.... combo.jsp and combo_action.asp


Combo.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script language="javascript">
<!--
   function submitForm()
   {
       myForm.submit();
   }
//-->
</script>

</head>

<body>
<p>
<!-- Open connection and execute query -->
<%

String region = null;
String selected = "";
String select_type = "";
Class.forName("org.gjt.mm.mysql.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
Statement statement = connection.createStatement();

String regiontype = request.getParameter("region_box"); // get value from itself (form page)
String regiontype2 = request.getParameter("region_box2");
ResultSet rs = statement.executeQuery("Select region from region");


%>
<!-- first select box -->
<form action="combo.jsp" method="post" name="myForm">
<select name="region_box" onchange="submitForm()">
<option value=""></option>
<%
while (rs.next()) {

region = rs.getString("region");

%>
<option value= "<%=region%>" <%=region.equals(regiontype)?" selected":""%> > <%=region%></option>
<% } %>
</select>
<!-- ends here ------>

<%
String query = "Select * from area";

if( region != null )
{
  query = "Select area from area where region='" + regiontype + "'";
}
ResultSet rs2 = statement.executeQuery(query);

%>
<select name="region_box2" onchange="submitForm()">
<option value=""></option>
<%
while (rs2.next()){
String area= rs2.getString("area");
%>
<option value= "<%=area%>" <%=area.equals(regiontype2)?" selected":""%> > <%=area%></option>
<% } %>
</select>
</form>

<br>
<form action="comb_action.jsp" method="post">
<input type="hidden" name="region" value="<%= regiontype %>">
<input type="hidden" name="region2" value="<%= regiontype2 %>">
<input type="submit" value="Submit">
</form>
<br>


<!-- Close the connection -->
<%
rs.close();
statement.close();
connection.close();
%>
</body>
</html>






Combo_action.jsp


<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<%

String value = request.getParameter("region");
String value2 = request.getParameter("region2");
%>

<%= value %>
<%= value2 %>

</body>
</html>