Reputation: 15
I have two select boxes.Both of them should be populated from database.Second select box should be populated based on the selected option in the first select box.Database connectivity is success and i am able to populate the first select box.But i dont know how to populate second select box based on the first.code i used to populate first select box is,
<select class="weekcombo">
<%
List list= new DataManager().getlist();
for(int i = 0; i < list.size(); i++) {
out.write("<option value=\""+ list.get(i)+ "\">"+ list.get(i));
}
%>
I dont know whether to use servlet or something else for this.
Upvotes: 0
Views: 1628
Reputation: 9579
Sagar Dalvi has a good solution. The only way to populate the 2nd select box based on the item selected in the first is with Javascript. This is because, unless you use Javascript, the contents of the 2nd select box would need to be known at page load time - before the user has made any selections.
Using Javascript, the page is ably to dynamically load the options into the 2nd select box when the user makes the selection in the first, using an AJAX call.
The only way round this without using javascript would be to have the form span more than one page, so the second select box is on the next page.
Upvotes: 0
Reputation: 200
For first select box you can populate values by default like you have mentioned in above code :
<select class="weekcombo" onchange="populateSecValues(this)">
<%
List list= new DataManager().getlist();
for(int i = 0; i < list.size(); i++) {
out.write("<option value=\""+ list.get(i)+ "\">"+ list.get(i));
}
%>
</select>
<select id="secBox" class="weekcombo">
</select>
Javascript : In urlString you can pass the first select box value like I have passed in below code snippet
function populateSecValues(obj){
// use here ajax call .. which will populate second box data
var firstBoxValue = obj.value;
var urlString ="your_action_url?firstBoxValue="+firstBoxValue ;
$.ajax({
type: "POST",
url: urlString ,
success: function(result) {
console.info("result"+result);
$("#secBox").html(result);
}
});
}
From server populate the values in the form of
<option value ="secBoxValue">secBoxValue</option>
Upvotes: 1