0

I have two dropdown fields in a JSP page and I have type4 connection with oracle 10g. I want that based on one dropdown selection I want that second dropdown should get filled by fetching data from database based on data in first dropdown automatically just like refreshing that JSP page or showing an alert something like "please wait". How can I do it in JSP-Servlet?

<select name="dropdown1">
    <option value="<%out.println(name);%>"><%out.println(name);%></option>
</select>

My objective is: This below dropdown should get filled base don above selection:

<select name="dropdown2">
    <option value="<%out.println(rollno);%>"><%out.println(rollno);%></option>
</select>

I have found one solution :

<body onload="setModels()">
<% // You would get your map some other way.
Map<String,List<String>> map = new TreeMap<String,List<String>>();
Connection con=null;
String vehtypeout="";

String vehtypeout1="";
try{
Class.forName("oracle.jdbc.driver.OracleDriver");


con=DriverManager.getConnection("");


      PreparedStatement ps=null;
ResultSet  rs=null;

ps=con.prepareStatement("select c1.name, c2.roll from combo1 c1 left join combo2 c2 on      c1.name=c2.name  order by name");

rs=ps.executeQuery();



while(rs.next()){

vehtypeout=rs.getString(1);

vehtypeout1=rs.getString(2);

map.put(vehtypeout, Arrays.asList((vehtypeout1)));// here i want to show multiple value of vehtypeout1 from database but only one value is coming from databse, how can i fetch multiple value?
map.put("mercedes", Arrays.asList(new String[]{"foo", "bar"}));

      }



rs.close();

ps.close();

con.close();
}

catch(Exception e){


out.println(e);

}
%>

<%! // You may wish to put this in a class
public String modelsToJavascriptList(Collection<String> items) {
StringBuilder builder = new StringBuilder();
builder.append('[');
boolean first = true;
for (String item : items) {
    if (!first) {
      builder.append(',');
    } else {
      first = false;
    }
    builder.append('\'').append(item).append('\'');
}
builder.append(']');
return builder.toString();
}

public String mfMapToString(Map<String,List<String>> mfmap) {
StringBuilder builder = new StringBuilder();
builder.append('{');
boolean first = true;
for (String mf : mfmap.keySet()) {
  if (!first) {
      builder.append(',');
  } else {
      first = false;
  }
  builder.append('\'').append(mf).append('\'');
  builder.append(" : ");
  builder.append( modelsToJavascriptList(mfmap.get(mf)) );
  }
  builder.append("};");
  return builder.toString();
  }
%>

<script>
var modelsPerManufacturer =<%= mfMapToString(map) %>
function setSelectOptionsForModels(modelArray) {
var selectBox = document.myForm.models;

for (i = selectBox.length - 1; i>= 0; i--) {
// Bottom-up for less flicker
selectBox.remove(i);
}

for (i = 0; i< modelArray.length; i++) {
 var text = modelArray[i];
  var opt = new Option(text,text, false, false);
  selectBox.add(opt);
  }
  }

  function setModels() {
  var index = document.myForm.manufacturer.selectedIndex;
  if (index == -1) {
  return;
  }

  var manufacturerOption = document.myForm.manufacturer.options[index];
  if (!manufacturerOption) {
  // Strange, the form does not have an option with given index.
  return;
  }
  manufacturer = manufacturerOption.value;

  var modelsForManufacturer = modelsPerManufacturer[manufacturer];
  if (!modelsForManufacturer) {
  // This modelsForManufacturer is not in the modelsPerManufacturer map
  return; // or alert
  }
  setSelectOptionsForModels(modelsForManufacturer);
}

function modelSelected() {
var index = document.myForm.models.selectedIndex;
if (index == -1) {
  return;
}
// alert("You selected " + document.myForm.models.options[index].value);
}
</script>
<form name="myForm">
<select onchange="setModels()" id="manufacturer">
  <% boolean first = true;
     for (String mf : map.keySet()) { %>
      <option value="<%= mf %>" <%= first ? "SELECTED" : "" %>><%= mf %></option>
  <%   first = false;
     } %>
</select>

<select onChange="modelSelected()" id="models">
  <!-- Filled dynamically by setModels -->
</select>


But i am getting only one value in vehtypeout1 where databse contains multiple values. How can i do it?

Tom
  • 761
  • 7
  • 22
  • 41
  • possible duplicate of [Populating child dropdownlists in JSP/Servlet](http://stackoverflow.com/questions/2263996/populating-child-dropdownlists-in-jsp-servlet) – BalusC Jan 04 '12 at 14:04
  • ya thanks but i have this problem: map.put(value of first combobox , Arrays.asList(new String[]{value of second combo box})); In database there are multiple values of second combo box but i am getting only one value in that second combo field. How can I resolve this? But i am getting multiple values in first combo field and like that i want multiple value in 2nd combo box. I have done like: while(rs.next()){ //got output value then: map.put(value of first combobox , Arrays.asList(new String[]{value of second combo box}));} – Tom Jan 05 '12 at 07:57

2 Answers2

0

Using jquery, bind a function to the onchange event of "combobox1" select box.

In that function, send an ajax request (you can use jquery get function) to a jsp page in your server.

In that jsp page, retrieve the relevant data from database and send the response back to the client with those data (may be you need to use JSON format).

In the jquery get function, you can add a callback function to execute after server send you back the response.

Inside that call back function, write the code to fill "combobox2" using response data sent by the server.

Manjula
  • 4,961
  • 3
  • 28
  • 41
0

You'll want an ajax call like below. Have your function that is called return a html-string of

"<option value='myVal'>myText</option>".

The jQuery/Ajax would be:

$("#ddl1").change(function() {
     $.ajax({
          url: "URLyouwanttoaddress",
          data: "myselection=" + $("#ddl1").val();
          type:"get",
          success: function(data) {
                     $("#ddl2").html(data);
          }
      });
});
Flater
  • 12,908
  • 4
  • 39
  • 62