cascading dropdown with Multiselect using Ajax and JSP - java

I am sending multiselect dropdown values to a JSP PAGE. Below is the AJAX code that send the multiselect values. The JSP PAge includes SQL query to read from database and show its values in another dropdown. Below code only display cascading dropdown values based on on select and not multiselect. It appears that only one value is sent to apps.jsp and not all values. I tried few changes and it didn't work. Below is the best working code available with me. Any help to get second dropdown display values based on multiselect from first dropdown? Single dropdown works fine with below code. Thank you.
<select multiple="multiple" name="RequirementFor" id="RequirementFor" onchange="showState(this.value);">
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
<div id="plat"><select name="Platform" id="Platform" multiple="multiple" onchange='showState2(this.value)'>
</select></div>
//AJAX Code
var xmlHttp ;
var xmlHttp;
function showState(str){
if (typeof XMLHttpRequest != "undefined"){
xmlHttp= new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp==null){
alert("Browser does not support XMLHTTP Request");
return;
}
var url="apps.jsp";
url +="?value=" +str;
xmlHttp.onreadystatechange = stateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function stateChange(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("plat").innerHTML=xmlHttp.responseText ;
}
}
below is code from JSP query(apps.jsp) page.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost", "username", "password");
Statement stmt;
ResultSet rs;
String[] funID= request.getParameterValues("value");
String conCat = "";
try{
if(funID.length>0)
{
for(int i=0;i<funID.length; i++)
{
conCat = funID[i] +" "+ "OR" + " "+ "FU_DEPARTMENT_ID= " + conCat;
}
conCat = conCat.substring(0, conCat.length() - 22);
}
}
catch(Exception e)
{out.println(e);}
String buffer="<select name='state' multiple='multiple'><option value='-1'>Select</option>";
try
{
String sqlSelect1="Select FU_ID, FU_NAME from UNIT where FU_DEPARTMENT_ID ="+conCat+" ORDER BY FU_NAME ASC";
stmt = con.createStatement();
rs = stmt.executeQuery(sqlSelect1);
while(rs.next()){
buffer=buffer+"<option value='"+rs.getString("FU_ID")+"'>"+rs.getString("FU_NAME")+"</option>";
}
buffer=buffer+"</select>";
response.getWriter().println(buffer);
stmt.close();
rs.close();
con.close();
}
catch(Exception e){
System.out.println(e);
}

I think you should change the way you get multi-values. Some thing likes this:
<select multiple="multiple" name="RequirementFor" id="RequirementFor" onchange='getMultiple(this);'>
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
<script>
var selected;
function getMultiple(ob) {
selected = new Array();
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[ i ].selected) {
selected.push(ob.options[ i ].value);
}
}
var str = "";
for (var i = 0; i < selected.length; i++) {
str += "&value=" + selected[i];
}
console.log(str);
// --> your ajax code
}
</script>

Related

How to append dynamically generated HTML table at the end of div, on selection of drop down present in the same div?

I am stuck in the following problem:
I have this div in html:
<div id="PieChart">
<label>Title of the pie chart:</label>
<input id="pieChartTitle" type="text">
<select id="xAxisList" onChange="showAxis('x')">
<option hidden="true"></option>
<option value="time">Time</option>
</select>
</div>
OnChange of drop down list I am calling a Javascript function, showAxis('x'), which dynamically generates HTML table. The code is below:
function showAxis(coordinate){
var axisList = coordinate + "AxisList";
var v = document.getElementById(axisList);
selectedAxisType = v.options[v.selectedIndex].value;
var dataArray = new Array();
selectedChartType = "PieChart";
var selectedChart = document.getElementById(selectedChartType);
var tr, td;
var table, tableBody;
var dropdown, opt, i;
table = document.createElement('TABLE');
dataArray = ["Years", "Seasons", "Months", "Weeks", "Days"];
table.setAttribute("id", "time"+axisList+"Table");
table.setAttribute("class", "time"+axisList+"Table");
table.width='100%';
tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
dropdown = document.createElement("select");
dropdown.setAttribute("id", "time"+axisList);
tr = document.createElement('TR');
tableBody.appendChild(tr);
td = document.createElement('TD');
td.width='40%';
td.appendChild(document.createTextNode("Time selection on the basis of:"));
tr.appendChild(td);
opt = document.createElement("option");
opt.hidden="true";
dropdown.options.add(opt);
for (i=0; i<dataArray.length; i++){
td = document.createElement('TD');
opt = document.createElement("option");
opt.text = dataArray[i];
opt.value = dataArray[i];
dropdown.options.add(opt);
td.appendChild(dropdown);
tr.appendChild(td);
}// END of Outer for loop
selectedChart.appendChild(table);
}// END of showAxis()
PROBLEM: This dynamically generated table in showAxis(coordinate) method gets appended before "xAxisList" drop down list, I want this TABLE as whole to be appended after the drop down list ("xAxisList").
I have spent much time on few blogs, but couldn't find anything helpful. I would be really thankful if someone helps me solving this issue. Thanks allot for your time and reading my question.
Check this JS FIDDLE v1.9.1 working with onchange in javascript instead of html.
JSFIDDLE v1
(function($){
$(function(){ //document.ready
$("#xAxisList").on('change', function() {
showAxis('x');
});
function showAxis(coordinate){
var axisList = coordinate + "AxisList";
var v = document.getElementById(axisList);
selectedAxisType = v.options[v.selectedIndex].value;
var dataArray = new Array();
selectedChartType = "PieChart";
var selectedChart = document.getElementById(selectedChartType);
var tr, td;
var table, tableBody;
var dropdown, opt, i;
table = document.createElement('TABLE');
dataArray = ["Years", "Seasons", "Months", "Weeks", "Days"];
table.setAttribute("id", "time"+axisList+"Table");
table.setAttribute("class", "time"+axisList+"Table");
table.width='100%';
tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
dropdown = document.createElement("select");
dropdown.setAttribute("id", "time"+axisList);
tr = document.createElement('TR');
tableBody.appendChild(tr);
td = document.createElement('TD');
td.width='40%';
td.appendChild(document.createTextNode("Time selection on the basis of:"));
tr.appendChild(td);
opt = document.createElement("option");
opt.hidden="true";
dropdown.options.add(opt);
for (i=0; i<dataArray.length; i++){
td = document.createElement('TD');
opt = document.createElement("option");
opt.text = dataArray[i];
opt.value = dataArray[i];
dropdown.options.add(opt);
td.appendChild(dropdown);
tr.appendChild(td);
}// END of Outer for loop
selectedChart.appendChild(table);
}// END of showAxis
});
})(jQuery);

List database values in a Combobox jsp with Bean Class Attached java

I am trying to list values from the database using JSP combobox like this:
My Vector Method:
public Vector getCampusCode(StudentRegistrationBean srb){
lgcampus = srb.getLgcampus();
Vector v = new Vector();
Connection conn = null;
try{
conn = db.getDbConnection();
Statement st = conn.createStatement();
String sql = "select CAMPUS_CODE from campus_master where CAMPUS_NAME = '" + lgcampus + "'";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
String camp = rs.getString("CAMPUS_CODE");
v.add(camp);
}
}catch(Exception asd){
System.out.println(asd.getMessage());
}
return v;
}
My JSP:
<jsp:useBean id="obj1" class="com.kollega.dao.StudentRegistrationDao" scope="page"/>
<jsp:useBean id="srb" class="com.kollega.bean.StudentRegistrationBean" scope="page"/>
<option selected value="SELECT">SELECT</option>
<c:forEach var="item" items="${obj1.campusCode(srb)}">
<option>${item}</option>
</c:forEach>
</select>
Of course the Combo is not getting Populated and all the other components on the page after the Combo are masked(disappear). If I remove the bean attached to the Vector without the Where Condition, my values are getting listed. But i need only specific values and not all. how Can i achieve this?
I just tried to populate the values in the combo box, it worked just fine. Please see the code below -- JSP
<jsp:useBean id="obj1" class="com.tutorial.ComboValues" scope="page"> </jsp:useBean>
<jsp:useBean id="obj2" class="com.tutorial.Input" scope="page"> </jsp:useBean>
<select>
<option selected value="SELECT">SELECT</option>
<c:forEach var="item" items="${obj1.getValues(obj2)}">
<option>${item}</option>
</c:forEach>
</select>
ComboValues class
public class ComboValues {
public Vector getValues(Input i){
Vector v = new Vector<String>();
if(i.getInput()==0)
v.add("worked");
else
v.add("it hurts");
return v;
}
}
Input class
public class Input {
int value = 0;
public void setInput(int i){
this.value = i;
}
public int getInput(){
return this.value;
}
}
The problem may be in the reference 'srb' you are passing to StudentRegistrationDao#getCampusCode since jsp:useBean will create a new instance of that type when there is no such object available. The other area to check is lgcampus = srb.getLgcampus(); whether it returns a proper value for the where clause. Hope this helps

Populate dropdown based on another dropdown selection

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?
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.
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);
}
});
});

json ajax problem

I am sorry to ask this but i've been working on this for hours and I can't figure it out on my own.
I have to use json for part of a project and I was able to get it to work but now it's not returning it back to the right jsp but instead just displaying the json jsp. I am pretty sure it is how I am receiving the json.
here are screen shots of what is happening:
this is the jsp that I need to use ajax on, I am wanting to populate the second dropdown using ajax:
this is what is happening instead, (it's the right data):
here is the code(sorry it's long):
-the jsp I am doing ajax on
<script type="text/javascript">
/**
* Utility function to create the Ajax request object in a cross-browser way.
* The cool thing about this function is you can send the parameters in a two-dimensional
* array. It also lets you send the name of the function to call when the response
* comes back.
*
* This is a generalized function you can copy directly into your code. *
*/
function doAjax(responseFunc, url, parameters) {
// create the AJAX object
var xmlHttp = undefined;
if (window.ActiveXObject){
try {
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
} catch (othermicrosoft){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {}
}
}
if (xmlHttp == undefined && window.XMLHttpRequest) {
// If IE7+, Mozilla, Safari, etc: Use native object
xmlHttp = new XMLHttpRequest();
}
if (xmlHttp != undefined) {
// open the connections
xmlHttp.open("POST", url, true);
// callback handler
xmlHttp.onreadystatechange = function() {
// test if the response is finished coming down
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// create a JS object out of the response text
var obj = eval("(" + xmlHttp.responseText + ")");
// call the response function
responseFunc(obj);
}
}
// create the parameter string
// iterate the parameters array
var parameterString = "";
for (var i = 0; i < parameters.length; i++) {
parameterString += (i > 0 ? "&" : "") + parameters[i][0] + "=" + encodeURI(parameters[i][1]);
}
// set the necessary request headers
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameterString.length);
xmlHttp.setRequestHeader("Connection", "close");
// send the parameters
xmlHttp.send(parameterString);
}
}//doAjax
/**
* Submits the guess to the server. This is the event code, very much
* like an actionPerformed in Java.
*/
function getSeats() {
// this is how you get a reference to any part of the page
var packInput = document.getElementById("pack");
var pack = packInput.value;
// while (packInput.childNodes.length > 0) { // clear it out
// aSeats.removeChild(aSeats.childNodes[0]);
// }
// an example of how to do an alert (use these for debugging)
// I've just got this here so that we know the event was triggered
//alert("You guessed " + seat);
// send to the server (this is relative to our current page)
// THIS IS THE EXAMPLE OF HOW TO CALL AJAX
doAjax(receiveAnswer, "ttp.actions.Sale3PackAction.action",
[["pack", pack]]);
// change the history div color, just 'cause we can
// var randhex = (Math.round(0xFFFFFF * Math.random()).toString(16) + "000000").replace(/([a-f0-9]{6}).+/, "#$1").toUpperCase();
// document.getElementById("history").style.background = randhex;
}
/**
* Receives the response from the server. Our doAjax() function above
* turns the response text into a Javascript object, which it sends as the
* single parameter to this method.
*/
function receiveAnswer(response) {
// show the response pack. For this one, I'll use the innerHTML property,
// which simply replaces all HTML under a tag. This is the lazy way to do
// it, and I personally don't use it. But it's really popular and you are
// welcome to use it. Just know your shame if you do it...
var messageDiv = document.getElementById("aSeats");
messageDiv.innerHTML = response.aSeats;
// replace our history by modifying the dom -- this is the right way
// for simplicity, I'm just erasing the list and then repopulating it
var aSeats = document.getElementById("aSeats");
while (aSeats.childNodes.length > 0) { // clear it out
aSeats.removeChild(aSeats.childNodes[0]);
}
for (var i = 0; i < response.history.length; i++) { // add the items back in
var option = aSeats.appendChild(document.createElement("option"));
option.appendChild(document.createTextNode(response.history[i]));
}
// reset the input box
//document.getElementById("pack").value = "";
}
</script>
<% Venue v = (Venue)session.getAttribute("currentVenue"); %>
<% List<Conceptual_Package> cpList = Conceptual_PackageDAO.getInstance().getByVenue(v.getId()); %>
What Packages do you want to see?
<form method="post" action="ttp.actions.Sale3PackAction.action">
<select name="packid" id="pack">
<% for (Conceptual_Package cp: cpList) { %>
<option value="<%=cp.getId()%>"><%=cp.getName1()%></option>
<% } %>
</select>
<input type="submit" value=" next " onclick="getSeats();"/>
</form>
<!--new-->
Available Seats:
<select name="eventSeatid" id="aSeats">
<option value="aSeats"></option>
</select>
<input type="button" value=" Add "/>
Selected Seats:
<form method="post" action="ttp.actions.sale4Action.action">
<select name="eventSeat2id" size="10" id="seat2">
<option value="seat2"></option>
</select>
</form>
<jsp:include page="/footer.jsp"/>
-the json jsp
<%#page contentType="text/plain" pageEncoding="UTF-8"%>
<jsp:directive.page import="java.util.*"/>
{
"history": [
<% for (String newSeats: (List<String>)session.getAttribute("newSeats")) { %>
"<%=newSeats%>",
<% } %>
]
}
-the action class
public class Sale3PackAction implements Action{
public String process(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String packid = request.getParameter("packid");
System.out.println("packid is: " + packid);
Conceptual_Package cp = Conceptual_PackageDAO.getInstance().read(packid);
request.setAttribute("cp", cp);
List<Physical_Package> ppList = Physical_PackageDAO.getInstance().getByConceptual_Package(cp.getId());
request.setAttribute("currentPack", ppList);
session.setAttribute("aSeats", null);
//return "sale3Pack_ajax.jsp";
//new
//HttpSession session = request.getSession();
// ensure we have a history
for (Physical_Package pPack: ppList){
try {
if (session.getAttribute("aSeats") == null) {
LinkedList aSeatsList = new LinkedList<String>();
session.setAttribute("aSeats", aSeatsList);
aSeatsList.add("Sec: " + pPack.getVenueSeat().getRowInVenue().getSectionInVenue().getSectionNumber() + " Row: " + pPack.getVenueSeat().getRowInVenue().getRowNumber() + " Seat: " + pPack.getVenueSeat().getSeatNumber());
session.setAttribute("newSeats", aSeatsList);
} else {
LinkedList aSeatsList = (LinkedList) session.getAttribute("aSeats");
aSeatsList.add("Sec: " + pPack.getVenueSeat().getRowInVenue().getSectionInVenue().getSectionNumber() + " Row: " + pPack.getVenueSeat().getRowInVenue().getRowNumber() + " Seat: " + pPack.getVenueSeat().getSeatNumber());
session.setAttribute("newSeats", aSeatsList);
}
} catch (DataException ex) {
Logger.getLogger(Sale3PackAction.class.getName()).log(Level.SEVERE, null, ex);
}
}
// next jsp page to go to
return "AjaxPack_json.jsp";
}
}
Hehe, I think we've all been in your place. Spending hours on something just to eventually realize that we overlooked some simple detail.
Read comments for more information...

getParameter only returning part of the string

Kindly assist here, the getParameter is only printing the first portion of the String element in the tag.
here is the select tag
<select name="ActionSelect" id="ActionSelect" >
<%Iterator itr;%>
<% List data = (List) request.getAttribute("data");
for (itr = data.iterator(); itr.hasNext();) {
String value = (String) itr.next();
%>
<option value=<%=value%>><%=value%></option>
<%}%>
</select>
and here is the code in the servlet
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/db";
Connection connection;
try{
this.ibrand = request.getParameter("ActionSelect");
pw.println(ibrand);
} catch (Exception e) {
pw.println(e);
}
Use double quotes around value in the option tag:
<option value="<%=value%>"><%=value%></option>
As it is right now, you probably have a space in your value so only the part of the value before space is returned.
Incidentally, it's not necessary to declare the Iterator uptop; you can do so directly in the for loop:
for (Iterator itr = data.iterator(); itr.hasNext();) {
Finally, consider using tag libraries instead of writing java code directly as scriptlets in your JSP.

Categories