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.Driv er");
Connection connection = DriverManager.getConnectio n("jdbc:my sql://loca lhost:3306 /test", "root", "");
Statement statement = connection.createStatement ();
ResultSet rs = statement.executeQuery("Se lect * 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("Se lect * 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!
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.
Connection connection = DriverManager.getConnectio
Statement statement = connection.createStatement
ResultSet rs = statement.executeQuery("Se
%>
<!-- 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("Se
<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!
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
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
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].sele cted) return selectbox.options[i];
}
function update( level ) {
var action = "?box1="+getSelected(form1 .box1).tex t;
if( level >= 2 ) action += "&box2="+getSelected(form1 .box2).tex t;
location.replace(action);
}
// -->
</script>
where as form1 ,box1 &nd box2 are
<form name="form1">
<select name="box1" onchange="javascript:updat e(1)">
<select name="box2" onchange="javascript:updat e(2)">
on load u populate box1 and box2 as u were doing
u can use
<script language="JavaScript">
<!--
function getSelected( selectbox ) {
for (i=0;i<selectbox.length;i+
if (selectbox.options[i].sele
}
function update( level ) {
var action = "?box1="+getSelected(form1
if( level >= 2 ) action += "&box2="+getSelected(form1
location.replace(action);
}
// -->
</script>
where as form1 ,box1 &nd box2 are
<form name="form1">
<select name="box1" onchange="javascript:updat
<select name="box2" onchange="javascript:updat
on load u populate box1 and box2 as u were doing
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
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.op tions; // 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[curState Index].len gth; i<n; i++ )
{
//// the line below no longer works in IE5 (it works in IE4 and NS4+).
// aryCityOpts[aryCityOpts.le ngth-1] = new Option(aryCityData[curStat eIndex][i] .text,aryC ityData[cu rStateInde x][i].valu e);
//// 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.le ngth-1].te xt = aryCityData[curStateIndex] [i].text;
aryCityOpts[aryCityOpts.le ngth-1].va lue = aryCityData[curStateIndex] [i].value;
}
}
// -->
</script>
</head>
<BODY onLoad='document.myform.se lState.foc us();'>
<FORM name='myform' method='post' action='whatever.asp' onSubmit='return(false);'>
State:
<SELECT name='selState' size='1' onChange='reloadCities(thi s.selected Index);'>
<OPTION value='0'></option>
<OPTION value='30'>California</opt ion>
<OPTION value='10'>Florida</option >
<OPTION value='20'>Texas</option>
</select><P>
City:
<SELECT name='selCity' size='1' onChange='alert(this.optio ns[this.se lectedInde x].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.od bc.JdbcOdb cDriver");
Connection con = null;
Statement stat = null;
PreparedStatement ps = null;
try {
con = DriverManager.getConnectio n("jdbc:od bc: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].sele cted) return selectbox.options[i];
}
function update( level ) {
var action = "?box1="+getSelected(form1 .box1).tex t;
if( level >= 2 ) action += "&box2="+getSelected(form1 .box2).tex t;
if( level >= 3 ) action += "&box3="+getSelected(form1 .box3).tex t;
location.replace(action);
}
// -->
</script>
</head>
<body>
<form name="form1">
box1:<p>
<select name="box1" onchange="javascript:updat e(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)?"se lected":"" %>><%=opti on%></opti on>
<%
}
rs.close();
%>
</select><p>
box2:<p>
<select name="box2" onchange="javascript:updat e(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)?"se lected":"" %>><%=opti on%></opti on>
<% }
rs.close();
ps.close();
%>
</select><p></p>
box3:<p>
<select name="box3" onchange="javascript:updat e(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)?"se lected":"" %>><%=opti on%></opti on>
<% }
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
<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
{
if ( curStateIndex < 0 ) return; // no state selected, so do nothing
var aryCityOpts = document.myform.selCity.op
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[curState
{
//// the line below no longer works in IE5 (it works in IE4 and NS4+).
// aryCityOpts[aryCityOpts.le
//// 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.le
aryCityOpts[aryCityOpts.le
}
}
// -->
</script>
</head>
<BODY onLoad='document.myform.se
<FORM name='myform' method='post' action='whatever.asp' onSubmit='return(false);'>
State:
<SELECT name='selState' size='1' onChange='reloadCities(thi
<OPTION value='0'></option>
<OPTION value='30'>California</opt
<OPTION value='10'>Florida</option
<OPTION value='20'>Texas</option>
</select><P>
City:
<SELECT name='selCity' size='1' onChange='alert(this.optio
<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.od
Connection con = null;
Statement stat = null;
PreparedStatement ps = null;
try {
con = DriverManager.getConnectio
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].sele
}
function update( level ) {
var action = "?box1="+getSelected(form1
if( level >= 2 ) action += "&box2="+getSelected(form1
if( level >= 3 ) action += "&box3="+getSelected(form1
location.replace(action);
}
// -->
</script>
</head>
<body>
<form name="form1">
box1:<p>
<select name="box1" onchange="javascript:updat
<%
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)?"se
<%
}
rs.close();
%>
</select><p>
box2:<p>
<select name="box2" onchange="javascript:updat
<%
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)?"se
<% }
rs.close();
ps.close();
%>
</select><p></p>
box3:<p>
<select name="box3" onchange="javascript:updat
<%
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)?"se
<% }
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.Driv er");
Connection connection = DriverManager.getConnectio n("jdbc:my sql://loca lhost:3306 /test", "root", "");
Statement statement = connection.createStatement ();
String regiontype = request.getParameter("regi on_box"); // get value from itself (form page)
String regiontype2 = request.getParameter("regi on_box2");
ResultSet rs = statement.executeQuery("Se lect 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(regiontyp e)?" 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(que ry);
%>
<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("regi on");
String value2 = request.getParameter("regi on2");
%>
<%= value %>
<%= value2 %>
</body>
</html>
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.
Connection connection = DriverManager.getConnectio
Statement statement = connection.createStatement
String regiontype = request.getParameter("regi
String regiontype2 = request.getParameter("regi
ResultSet rs = statement.executeQuery("Se
%>
<!-- 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(regiontyp
<% } %>
</select>
<!-- ends here ------>
<%
String query = "Select * from area";
if( region != null )
{
query = "Select area from area where region='" + regiontype + "'";
}
ResultSet rs2 = statement.executeQuery(que
%>
<select name="region_box2" onchange="submitForm()">
<option value=""></option>
<%
while (rs2.next()){
String area= rs2.getString("area");
%>
<option value= "<%=area%>" <%=area.equals(regiontype2
<% } %>
</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("regi
String value2 = request.getParameter("regi
%>
<%= value %>
<%= value2 %>
</body>
</html>
String typefood;////////// give dynamic value to your combobox as <%=typefood%>
rset = stmt.executeQuery(str);
%>
<select name="type_of_food" id="<%=typefood%>"style="w
<%
while (rset.next())
{
String type = rs.getString("type"); %>
<option value="<%=type%>" <%=((type.toString().equal
}
%>
</select>
<%