hi all!
i am new to jsp, i have two comboboxes,in which values of 2nd combo box are linked two first combo box and we get values for both these boxes from database.

table1

(pk)itemno:text
itemname:text (no duplicates)

table2

(pk)itemno:text(duplicates)
(pk)pcode:text
pname:text(no duplicates)

i want to display..

combobox1:itemname
combobox2:pname

Note: Both Values of combobox are to be retrieved from database.

when user select itemname corresponding values of pname should be displayed. I went through google and some threads of this forum and found some info but there option values are not retrieved from database(given in code itself), but i'm puzzled from retrieving 1st combo values and select one to retrieve the values of 2nd combo.

Hope i have made my question clear. Thank You all!

Recommended Answers

All 17 Replies

Can I see you code please? Start to code and post your problems. Definitely, we will help you.

Can I see you code please? Start to code and post your problems. Definitely, we will help you.

Many thanks. Well i started coding and succesful in retrieveing first combox values from database and stored the selected value in a hidden type input now i dunno know to proceed frm here.

my problem is that, i will use <form action="servlet "> and retrieve values from database using selected value in combobox1 (getParameter()).now how can i send back these reteieved values of combobox 2 back to jsp...??

my code trail.jsp

<%@ page language="java" contentType="text/html" import="java.sql.*" %>

<html>
<head><title>select  box demos</title>
<script type="text/javascript">
function redirect()
{
 var index=document.myForm.selbox.selectedIndex;
 document.myForm.selv.value=document.myForm.selbox.options[index].value;
document.write(document.myForm.selv.value);// stored selected value in hidden type value
}

</script>
</head>
<body>
<form name="myForm">
<table>
<%
 try
 {
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  Connection conn=DriverManager.getConnection("jdbc:odbc:trail");
  try
  {
   String itname[]={};
   
   int i=0,j=0,m=0;

   String str1="select * from table1";
   PreparedStatement stmt1=conn.prepareStatement(str1);
   ResultSet rs1=stmt1.executeQuery();

   itname=new String[100];
 
   while(rs1.next())
   { 
    itname[m]=rs1.getString(2);
    m++;
   }
    
   
   for(j=m;j<100;j++)
   {
    itname[j]="null";
   }
   

  out.println("<tr>");
  out.println("<td>Item Type:</td>");
  out.println("<td>"); 
%>
 <select name="selbox" id="sel" onchange=redirect(this.form) >
<%
  while(i<itname.length)
  {
   if(itname[i]!="null")
    out.println("<option value="+itname[i]+">"+itname[i]+"</option>");
    i++;
  }
  out.println("</select>");

  }
  catch(SQLException e)
  {
   out.print("SQL Not Executing");
  }
 } 
 catch(Exception e)
 {
  e.printStackTrace();
 }
%>
<input type="hidden" name="selv" >
</table>
</form>
</body>
</html>

Use Ajax for your reqirement

i am giving solution to your problem

first create 2 jsp for your reqirement

first you show the one list itemname in the first jsp page
when user select the option from the list ,call ajax function in the
first jsp page ,and reterieve the value from the database according
to the itemname
i show the code
this is your first jsp page itemname.jsp

<html>
<head>






</head>



<body>
<script type="text/javascript">function ajaxFunction()
{var xmlHttp;
try
  {  // Firefox, Opera 8.0+, Safari 
   xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {  // Internet Explorer 
   try
    {    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    }
  catch (e)
    {    try
      {      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");      }
    catch (e)
      {      alert("Your browser does not support AJAX!");      return false;      }    }  }
  xmlHttp.onreadystatechange=function()
    {
	   //alert("i m  not  in ready state");
	   
	    if(xmlHttp.readyState==0)
      {
      //document.myForm.time.value=xmlHttp.responseText;
	    alert("The request is not initialized");
	  
	   

	   
	  
      }
	      if(xmlHttp.readyState==1)
      {
      //document.myForm.time.value=xmlHttp.responseText;
	    alert("The request has been set up");
	  
	   

	   
	  
      }
	  
	  
	  
	        if(xmlHttp.readyState==2)
      {
      //document.myForm.time.value=xmlHttp.responseText;
	    alert("The request has been sent");
	  
	   

	   
	  
      }
	  
	  	        if(xmlHttp.readyState==3)
      {
      //document.myForm.time.value=xmlHttp.responseText;
	    alert("The request is in process");
	  
	   

	   
	  
      }
	   
	  
	   
	  
	  
	   
	   
	  
    if(xmlHttp.readyState==4)
      {
      //document.myForm.time.value=xmlHttp.responseText;
	    //alert("i m in ready state");
	  
	   document.getElementById("theResponse").innerHTML = xmlHttp.responseText;

	   
	  
      }
    }
	      var itemname=document.myForm.itemname.value;
	      var url="getProduct.jsp";
          url=url+"?itemname="+itemname+"&sid="+Math.random();
          //url=url+"&sid="+Math.random();

	
	  
         xmlHttp.open("GET",url,true);
         xmlHttp.send(null); 
   }
  
  </script>
select itemname:<form name="myForm" onBlur="ajaxFunction();" >
  <select  name="itemname">
  <option value="computer">computer</option>
  <option value="cars">Cars</option>
  
  </select>

<div id="theResponse">

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

Now your second Jsp page
getProduct.jsp

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>

<%
// open the database connection and get the ResultSet
// according to your itemname
 // take example 
// ResultSet rs=select pname from product where itemname='"+request.getParameter(itemname)+"' ;

%>
 <select  name="pname">

<%   while(rs.next())
   { %>
    <option value="<%=rs.getString(1)%>">"<%=rs.getString(1)%>"</option>
   
 <%  } %>

 </select>
 
 
     





%>



</body>
</html>

try it

Promise me that you will the follows Peter budo's post.

A code I am posting here is a solution of your current problem. It can't help to solve your Java Web Development problems.

DB.java - Place this java file in WEB-INF/classes folder and compile it.

package com.me;

import java.sql.*;
import java.util.*;

public class DB
{
   static String url="jdbc:odbc:sampledb";
   static String username="your_user_name";
   static String password="your_password";
   static String driver="sun.jdbc.odbc.JdbcOdbcDriver";
    static{
         try {
                 Class.forName(driver);
             }catch(Exception ex) {}
   }
  public static Connection getCn() throws Exception {
         return DriverManager.getConnection(url,username,password);  
  }
  public static int execute(String sql) throws Exception {
         Connection cn=getCn();
         Statement st=cn.createStatement();
         int i=st.executeUpdate(sql);
         st.close(); cn.close();
         return i;
  }
  public static Object getValue(String sql) throws Exception{
         Connection cn=getCn();
         Statement st=cn.createStatement();
         ResultSet rs=st.executeQuery(sql);
         Object i=null;
          if(rs.next())
                i=rs.getObject(1);
         rs.close();
         st.close(); cn.close();
         return i;
  }
  
  public static String getCombo(String sql,String sel) throws Exception{
         Connection cn=getCn();
         Statement st=cn.createStatement();
         ResultSet rs=st.executeQuery(sql);
         if(sel==null) sel="";
         
         String result="<option value=''>Select</option>";
         String value="";
         String text="";
         while(rs.next()){
                value=rs.getString(1); text=rs.getString(2);
 
                if(value.equals(sel)) {
                  result=result + "<option value=\"" + value + "\"  selected=\"selected\" >" + text + "</option>";

                }
                else{
                   result=result + "<option value=\"" + value + "\">" + text + "</option>";

                } 
          }
         rs.close(); st.close(); cn.close();  
         return result;
   }
}

and a page1.jsp

<?% page language="java" import="java.sql.*" %>

<%
   String item=request.getParameter("item");
   if(item==null) item="";

%>
<form name="form1" method="post" action="page1.jsp">
   <select name="item"  onchange="form1.submit()">
       <%=com.me.DB.getCombo("select itemno,itemname from item",item) %>
   </select>

   <select name="prod">
        <%=com.me.DB.getCombo("select pcode,pname from product where itemno='" + item + "'",item) %>
   </select>
</form>

Use Ajax for your reqirement

i am giving solution to your problem

first create 2 jsp for your reqirement

first you show the one list itemname in the first jsp page
when user select the option from the list ,call ajax function in the
first jsp page ,and reterieve the value from the database according
to the itemname
i show the code
this is your first jsp page itemname.jsp

Thank You amarjeetsingh for spending your valuable time on answering this.

well i heared AJAX will solve the problem but i have no time (deadline of this project) to learn AJAX. So, looking for other alternative, anyway i managed to get through your code and going to work on it.

</script>
select itemname:<form name="myForm" onBlur="ajaxFunction();" >
<select name="itemname">
<option value="computer">computer</option>
<option value="cars">Cars</option>

</select>

Seems like you have given values directly , i want these values from database too. Wat's the job of this AJAX Script u given? .
Does it gets values for itemname from database?

Once again Many Thanks.Added Reputation.

Thank you adatapost , with your motivation i started coding and it's very kind of you for helping me to solve this.

Promise me that you will the follows Peter budo's post.

Sure, I Promise.

A code I am posting here is a solution of your current problem. It can't help to solve your Java Web Development problems.

what kind of java web development problems?

I have seen your code and not familiar with some lines anyway got some sense of it, i will get back to you as soon as i run this code.

Thanks for Spending your valuable time.Added Reputation.

you want to show the itemname from the database
it is very easy,

in your servlet
by open a dao connection
get all the data from the database
set into the ArrayList
then in the servlet
set the ArrayList

request.setAttribute("arr",ArrayList);

now
in the jsp

<select name="itemname">
<c:forEach   items="${arr}"   var="show" >
 <option value=" ${show}">${show}</option>


</c:out>


</c:forEach>

</select>

but it will be in your first jsp page

then use the Ajax in the first jsp page for the second jsp page

Hai adatapost compiled ur java code but no results it gives Http status 500 error...anyway Thanks 4 ur effort.

Just now finished tutorial on AJAX now i'm moving to amarjeetsingh's AJAX code...will be back after testing it!!!

hi amarjeetsingh i have coded as you said

2 Jsp pages
itemname.jsp
getproduct.jsp

the problem here is the value of itemname selected was not sent to secondpage (request.getparameter not working) this is wat i get when i run the code
[IMG]http://i43.tinypic.com/dwqve1.jpg[/IMG]

i am giving you the 2 jsp pages and access database Zipped and i put them in attachment down here, Could u please help me to run this code, i would be very greatful to you.

Thank You,
sriups

Once you decide to follow MVC standard, you can contact me.
Secondly you should start learning about basic deployment with Tomcat

Once you decide to follow MVC standard, you can contact me.
Secondly you should start learning about basic deployment with Tomcat

of course i follow mvc standard i'm using jbdc inside jsp here just for testing purpose i'm going to convert it to MVC standard later.

of course i follow mvc standard i'm using jbdc inside jsp here just for testing purpose i'm going to convert it to MVC standard later.

You should do it from beginning, that way you wouldn't be pulling double shift and same goes for us

the best answer is ajax and actually you do not to learn ajax just copy
the code i will gave and follow the guidlines copy and paste the attached file into your project folder :

1- copy and paste the attached file into your project folder


2- copy the following code and paste into the head of you jsp file

<script type="text/javascript" src="prototype.js"></script>
<script>
function item_code1(value){

var myAjax1=new Ajax.Request('itemcode1.jsp',{
method: 'post',postBody:'id='+value, onSuccess: function(transport) {
var itemcode1=$('itemcode1');
itemcode1.update(transport.responseText);
}
});
}

3- in your itemname combobox html make it exactly like follow <select name="itemname1" size="1" id="first1" onchange="item_code1($('first1').value);"> 4- copy and paste the following code where do you want the itemcode to be appeare <div id="itemcode1"> </div> 5- now you just need to open new jsp file and copy write the following

<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %> 


<%
String id=request.getParameter("id");
Vector v1,v2;

jmm.Database database = new jmm.Database(pageContext.getServletContext().getRealPath("/WEB-INF/config.txt")); // depend on  yours 
database.jdbcConnect();
String sql;

sql = "select itemcode from item where itemname='"+id+"'";



out.print("<select name=itemcode1 id=\"itemcode \">");

 v1=database.jdbcMultipleRowQuery(sql);
 if(v1.size()!=0){
	for(int i=0;i<v1.size();i++){
	v2 = (Vector)v1.elementAt(i);
			for(int j=0;j<v2.size();j++){
				out.print("<option>"+v2.get(0)+"</option>");				
			}
	}
	out.print("</select>");
	
	}else{
	
	}




database.jdbcConClose();
database = null;

%>

5- i wish it will help ,

just inform me if it does not work

CoSIS1>the best answer is ajax and actually you do not to learn ajax just copy the code i will gave and follow the guidlines copy and paste the attached file into your project folder.

How did you know AJAX? just copy the code?

Wrap up source code with bb code tags.
Read
How to use BB code tags?

am new member here, and i just wanted to help here
plus this code is working , i have used it before .
actually i know some in ajax that helped me before in my projects

<html>
<head><title>Sales Page/title></head>
<body>
<script type="text/javascript">
function ajaxFunction()
{
 var xmlHttp;
 try
 {  // Firefox, Opera 8.0+, Safari 
   xmlHttp=new XMLHttpRequest();
 }
 catch (e)
 {  // Internet Explorer 
   try
   {    
     xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    
   }
   catch (e)
   {    
     try
     {      
       xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");      
     }
     catch (e)
     {      
       alert("Your browser does not support AJAX!");      
       return false;      
     }    
   }  
 }
 
 xmlHttp.onreadystatechange=function()
 {
   //alert("i m  not  in ready state");
	   
   if(xmlHttp.readyState==0)
   {
     //document.myForm.time.value=xmlHttp.responseText;
     alert("The request is not initialized");
   }
   if(xmlHttp.readyState==1)
   {
     //document.myForm.time.value=xmlHttp.responseText;
     alert("The request has been set up");
   }
   if(xmlHttp.readyState==2)
   {
     //document.myForm.time.value=xmlHttp.responseText;
     alert("The request has been sent");
   }
   if(xmlHttp.readyState==3)
   {
     //document.myForm.time.value=xmlHttp.responseText;
     alert("The request is in process");
   }
   if(xmlHttp.readyState==4)
   {
     //document.myForm.time.value=xmlHttp.responseText;
     //alert("i m in ready state");
     document.getElementById("theResponse").innerHTML = xmlHttp.responseText;
   }
 }
	      
	      
 var itemname=document.myForm.itemname.value;
 var url="getProduct.jsp";
 url=url+"?itemname="+itemname+"&sid="+Math.random();  //url=url+"&sid="+Math.random();

 xmlHttp.open("GET",url,true);
 xmlHttp.send(null);
}
</script>
select itemname:
<form name="myForm">
/*
  wrong code------
  <option>processors</option>
<option>speakers</option>
<option>monitor</option>
<option>mouse</option>

due to this code you can not get
the value in the request.getParameter("itemname");

*/

<!-- right code   --->

<select  name="itemname" onChange="ajaxFunction();">
<option value="processors">processors</option>
<option value="speakers">speakers</option>
<option value="monitor">monitor</option>
<option  value="mouse">mouse</option>





</select>
<div id="theResponse">

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

Now your second page getproduct.jsp

i have removed un necessary code

<%@ page language="java" contentType="text/html" import="java.sql.*" %>

<html>
<head><title>select  box demos</title></head>
<body>

<%
 try
 {
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  Connection conn=DriverManager.getConnection("jdbc:odbc:select");
  try
  {

   String val=request.getParameter("itemname");

   //String val1="speakers";
   //String val2="processors";
   

  // String itname[]={};
   
 //  int i=0,j=0,m=0; 

   String str="select * from stocks where item_name=?";

   PreparedStatement stmt=conn.prepareStatement(str);

   stmt.setString(1,val);

   ResultSet rs=stmt.executeQuery();

  /*   itname=new String[100];
 
   while(rs.next())
   { 
       itname[m]=rs.getString(3);
        m++;
   }
    
   
   for(j=m;j<100;j++)
   {
    itname[j]="null";
   }  */
    
%>

Prod Name:  <select name="productname">
<%
  while(rs.next())
  {
   //  if(itname[i]!="null")
       out.println("<option value="+rs.getString(3)+">"+rs.getString(3)+"</option>");
      //i++;
  }
     // out.println("</select>");

  }
  catch(SQLException e)
  {
      out.print("SQL Not Executing");
  }
 } 
 catch(Exception e)
 {
  e.printStackTrace();
 }
 
   finally
	        	  {
	        		  
	        		  
	        		  try
	        	    	{
	        	    	    if(rs!=null)
	        	    	      {
	        	    	     	     rs.close();
	        	    		         rs=null;
	        	    		        	    		
	        	    	      }
	        	    	     if(stmt!=null)
	        	    	      {
	        	    	     	     stmt.close();
	        	    		          stmt=null;
	        	    		        	    		
	        	    	      }
	        	    	     
	        	    	     if(conn!=null)
	        	    	      {
	        	    	     	     conn.close();
	        	    		          conn=null;
	        	    		        	    		
	        	    	      }
	        	    	     
	        	    	   
	        	    	 }catch(SQLException e)
	        	    	 {
	        	    	 	 out.print("SQL Not Executing"+e);
	        	    	 }
	        	    	
	        		  
	        		  
	        		  
	        	  }
	        	 
 
 
%>
</select>

</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.