Link to home
Start Free TrialLog in
Avatar of Sh_Rashed
Sh_Rashed

asked on

Drop Box menu selection changing dynamicly

i am using JSP - Servlet and oracel

I have two Drop Box menu in a form..

First one .. is populated from the Dtatabase ( The selection options come from database) .. for example all Item model I have in my store..

Second one .. is populated from the dtatabase .. according to the Selection of the first one .. for example all serial Number of such Item model have been selected in the first Drop menu Box.

so, I need second drop box to be changed according to the user selection in the first drop box menu ..?

How I can do it ? plz help =)
Avatar of jaggernat
jaggernat

well, I had a similar requirement and I did it this way:

Write a java util class and in that util class, call the database and get the data. Store the data in xml format in a StringBuffer variable.

In your front-end you will have a jsp with javascript functions.  Load the StringBuffer (containing the xml data) in your javascript.
Now in your javascript use Xpath to traverse through the xml. So once the user changes the first drop-down,  write a onChange() (in first drop-down) which will call the function in javascript and that function will change the values in the  second drop-down accordingly.

Avatar of Sh_Rashed

ASKER

I have written those two methods in Controller Class..

public Vector getOptionSelection1 (){} // this methos return the selection options of drop box menu..

public Vector getOptionSelection2(String option){} // this method will return selection option in the second drop box.

so .. I will write a method ..ToXML (Vector v){}// return String in xml format..

Then How I can use javaScript (StringBuffer) .. I don't have any idea .. Help me  plz .. =)
your stringbuffer would contain data in xml format like this

example:

<state>
  <region>
       <county>
        .....

       </county>
   </region>
</state>
and then use xpath in your javascrpt and navigate through the xml and fill the dropdowns

go though this
http://developer.mozilla.org/en/docs/Introduction_to_using_XPath_in_JavaScript
for this u can use Ajax.. when the user select a particular item then using javascript the u send a request to a servlet in the server with the item the user selected as a parameter. Then the servlet will return all the items for the second list box. Then using the javascript u can add all the elements into the list.

This will work fine...

below link will detail u about Ajax,javascript and servlet
http://www-128.ibm.com/developerworks/library/j-ajax1/
i agree with deeppra. ajax is another option.
I have just posted a sample code which you can refer to.
https://www.experts-exchange.com/questions/22052625/struts-drop-down.html

You probably can change it to directly open as text instead of xml.
Let me know if you have any query.
Hi experts,

I like Ajax that is really what I need in this case. I have read the IBM article about Ajax ..I love it .. Thanks deeppra  =)

Now, I need to modify the javaScript in that article (http://www-128.ibm.com/developerworks/library/j-ajax1/) for my case .. I tried but it didn't work .. I don't have any experience with javaScript ..

in the form.html :

<p>Item Model : <select size="1" name="ItemModel"  onchange="getSN()">
      <option>Hp500</option>
      <option>Hp600</option>
      <option>Hp700</option>
      </select>

what I should pass with .. getSN()? <---?

This is my javaScript:


function getSN(itemModel) {

 var req = newXMLHttpRequest();

 req.onreadystatechange = getReadyStateHandler(req, updateSN);
 
 req.open("POST", "item.do", true);
 
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 
req.send("itemModel="+itemModel);}

---------------------------------------------------------------------------------------------

function updateSN(snXML) {
 
var root = sntXML.getElementsByTagName("root")[0];

 var generated = root.getAttribute("generated");
 
if (generated > lastUpdate) {
   
   lastUpdate = generated;
   
   var contents = document.getElementById("dropdown2");
   
   contents.innerHTML = "";

   var items = root.getElementsByTagName("Item");
   
for (var I = 0 ; I < items.length ; I++) {

     var itemsn = itemsn[I];
 
     var name = item.getElementsByTagName("SN")[0].firstChild.nodeValue;
     

     var listItem = document.createElement("li");
     listItem.appendChild(document.createTextNode(name));
     contents.appendChild(listItem);
   
}}}

----------------------------------------------------------------------

In the Servlet ..

request.getParameter("ItemModel") (<- which javaScript suppose to send to the Servlet) return null value..

-----------------------------------------------------------------------

The XML that will be send back to the XMLHttpResponse looks like the following:

<root>

<Item>
<SN> 122334 </SN>
<SN> 345666 </SN>
<Item>

<root>

----------------------------------------

I don't have any problem in the server side .. but in javaScript ?

Any Help ?!

You will pass in the selected value to the method getSN().
Example:
<select size="1" name="ItemModel"  onchange="getSN(this.options[this.selectedIndex])">
i think u have only Nullpointer exception... the reason is u used itemModel in the javascript
req.send("itemModel="+itemModel);}

but in u r servlet u r using caps ItemModel this is the reason for NullPointer Exception

In the Servlet ..

request.getParameter("ItemModel") (<- which javaScript suppose to send to the Servlet) return null value..


So in u r servlet use itemModel
regards
Pradeep D
Thank u boonleng and deepra ..

req.send("itemModel="+itemModel);} <-- I have changed it ..

Now . in the servlet . I print the request.getParameter("itemModel") .. as the following:

String itemModel = req.getParameter("itemModel");
       
System.out.println("---------- this is the model: ------- "+itemModel);

it prints : ---------- this is the model------------:  [object]

When I hard coded the value in the javaScript as the following:

req.send("itemModel= hp500");  .. it prints correctly in the Servlet.

I think the problem in the form.html:

<select size="1" name="itemModel" onchange= "getSN(this.options[this.selectedIndex])" > <-- I think this line doen't pass the value to the java Script

any idea?
the parameter in the getSN gives u the index of the selected item... and also change the <option> tag include the value attribute to it
like this
<option value="hp500">hp500</option>

in the javascript


instead of the this line
<select size="1" name="itemModel" onchange= "getSN(this.options[this.selectedIndex])" > 

change it like this
<select size="1" name="itemModel" onchange= "getSN(this.options[this.selectedIndex.value])" > 

so this directly passes the value of the selected item and that one will be added in the request
try this one and send me the reply
sorry this the correct is this
<select size="1" name="itemModel" onchange= "getSN(this.options[this.selectedIndex].value)" > 
deeppra .. Thank u for ur time .. (F) ..

I changed the selection

<p>Item Model :<select size="1" name="itemModel" onchange= "getSN(this.options[this.selectedIndex.value])" > 
      <option name ="itemModel" value="HP500">Hp500</option>
      <option name ="itemModel" value="HP600">Hp600</option>
      <option name ="itemModel" value="HP700">Hp700</option>
      </select></p>


and when I printed the request.getParameter("itemModel") ..

I got:

---------- this is the model:  undefined -----------------------


I think I will give up .. and jst put field instead of drop menu :D
Item Model :<select size="1" name="itemModel" onchange= "getSN(this.options[this.selectedIndex.value])" >

change like this

Item Model :<select size="1" name="itemModel" onchange= "getSN(this.options[this.selectedIndex].value)" >
^
Thank u .. that worked .. but .. I didn't get the reponse .. I don't know what is excatly the problem !

if I didn't receive XMLHttpResponse or not complete .. OR the problem in present the receivd data .. so how I can make sure that I have received the data?

This is the form.html:

<form name = "ItemsForm" method="POST" action="cart.do">
      
<p>Item Model :<select size="1" name="itemModel" onchange= "getSN(this.options[this.selectedIndex].value)" >
 
      <option name ="itemModel" value="HP500">Hp500</option>
      <option name ="itemModel" value="HP600">Hp600</option>
      <option name ="itemModel" value="HP700">Hp700</option>
      </select></p>
       
      <p>Item Serial Number : <select size="1" name="ItemSN" id ="dropdown2"></select></p>
      
       
      
<p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>


-------------------------------------------


This is my JavaScript that will present the data... is there any error?!

function updateSN(snXML) {
 
var root = sntXML.getElementsByTagName("root")[0];

/* <-- ItemsForm is the name of the form in the form.html - and dropdown2 is the id of serial Number selection--> */

var contents = document.ItemsForm.getElementById("dropdown2");  

   
contents.innerHTML = "";

var items = root.getElementsByTagName("Item");
   

for (var I = 0 ; I < items.length ; I++) {

     var item = items[I];
 
     var name = item.getElementsByTagName("SN")[0].firstChild.nodeValue;
     

     var listItem = document.ItemsForm.createElement("option");
     
     listItem.appendChild(document.createTextNode(name));
     
     contents.appendChild(listItem);
   
}

 }

----------------------

The XML looks like:

<root>

<item>

<SN> 123 </SN>

</item>

<item>

<SN> 124 </SN>

</item>

 </root>

----------------------

This is the first time for me to write javaScript  =(

so ,, !? =)
okay, in ur servlet u print the values and see whether its coming correctly or not
in the Servlet it comes correctly ..

This is my doPost ..

  public void doPost(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
       
       
        String itemModel = req.getParameter("itemModel");
       
        System.out.println("---------- this is the model---------: "+itemModel);
       
        Vector result = getAllSN(itemModel);
       
        String snXML = toXML(result);
       
        System.out.println("This is:-----------------------------------"+snXML);
       
        res.setContentType("text/xml");
       
        res.getWriter().write(snXML);
       
       
       
       
       
    }

and  it is print the value correctrly and create the xml correctly..
then what output u r getting in the browser??
close ur outputstream like this
res.getWriter().write(snXML);
res.getWriter().close();

also see the output page source in the browser...
In the Browser .. when I select from Item Model (First drop down) .. The second drop down menu not fill with the serial Number and I got error in the page.
instead of creating XML message u send the itemModel with some delimiters like this
itemModel1#itemModel2#itemModel3
so in the javascript u split it and put it in the box
check in the javascript callback function whether u r getting the XML response from the server
function getReadyStateHandler(req, responseXmlHandler) {

  // Return an anonymous function that listens to the
  // XMLHttpRequest instance
  return function () {

    // If the request's status is "complete"
    if (req.readyState == 4) {
     
      // Check that a successful server response was received
      if (req.status == 200) {

        // Pass the XML payload of the response to the
        // handler function
        responseXmlHandler(req.responseXML);

      } else {

        // An HTTP problem has occurred
        alert("HTTP error: "+req.status);
      }
    }
  }
}


-----------------

I think there is error in extract xml javascript ?
>>>I think there is error in extract xml javascript ?

so instead of using XML you send the itemModel in the response with out any XML code like this
itemModel1#itemModel2#itemModel3
ummm . the String sns should be like this:

String sns = "123344#122334#1233445"; ?

Then how should I change the extract javaScript :

unction updateSN(snXML) {
 
var root = sntXML.getElementsByTagName("root")[0];

var contents = document.ItemsForm.getElementById("dropdown2");
   
contents.innerHTML = "";

var items = root.getElementsByTagName("Item");
   

for (var I = 0 ; I < items.length ; I++) {

     var item = items[I];
 
     var name = item.getElementsByTagName("SN")[0].firstChild.nodeValue;
     

     var listItem = document.ItemsForm.createElement("option");
     
     listItem.appendChild(document.createTextNode(name));
     
     contents.appendChild(listItem);
   
}

 }

?
Strign sns = "12345#12233#1223" <-- This will be getting from the database according to the selection in the first drop box
okay after getting the string in the javascript use some of the string functions to extract each item
for more information on string function in javascript check this
http://www.javascriptkit.com/javatutors/string2.shtml
http://richardbowles.tripod.com/javascript/section10/lesson10.htm

i think this will help u
I wrote this javaScript and it didn't work  (Error on the page).. I think there is a syntax error ..

This is my javaScript .. check it plz

function writeSN(snXML){

var result = snXML;

array2 = result.split("#");

var contents = document.getElementById("dropdown2");
   contents.innerHTML = "";



for ( var I = 0 ; I < array2.length ; I++){

  var sn = array2[I]

  var listItem = document.ItemsForm.createElement("option");


 listItem.appendChild(document.createTextNode(sn));
     
contents.appendChild(li);



}
}
what error u r getting ?? send me the line number and the details so that i can fix it
This is the String that the servlet print ..

String sn = "66353528292#1111111111111111#77777777666666"
use this code for updating the dropdown box
function writeSN(snXML){

var result = snXML;

array2 = result.split("#");

var dropdown = document.getElementById("dropdown2");

for ( var I = 0 ; I < array2.length ; I++){
   dropdown.options.add(new Option(array2[I],array2[I]));
}
}

see this for dropdown box
http://www.quirksmode.org/js/options.html
if u have any errors then send me  the full code and the line number where u r getting error
Errors on the Page .. :(((

I tried ur javaScript .. it didn't work .. I did some changes:

function writeSN(snXML){

var result = snXML;

array2 = result.split("#");



for ( var I = 0 ; I < array2.length ; I++){
   
document.forms['ItemsForm'].ItemSN.options[I] = new Option(array2[I],array2[I]);



}}


How I make sure that I have received response ?

This is my handler function .. that waiting for the response


function getReadyStateHandler(req, responseXmlHandler) {

  // Return an anonymous function that listens to the
  // XMLHttpRequest instance
  return function () {

    // If the request's status is "complete"
    if (req.readyState == 4) {
     
      // Check that a successful server response was received
      if (req.status == 200) {

        // Pass the XML payload of the response to the
        // handler function
        responseXmlHandler(req.responseXML);

      } else {

        // An HTTP problem has occurred
        alert("HTTP error: "+req.status);
      }
    }
  }
}

u show some alert or otherwise in the alert message give like this
alert(req.responseXML);
When I added alert(req.responseXML); in the following sequence:

  if (req.status == 200) {

        // Pass the XML payload of the response to the
        // handler function
        alert(req.responseXML);
        responseXmlHandler(req.responseXML);

      }

it shows alert message : [object]

but when I added after:

  if (req.status == 200) {

        // Pass the XML payload of the response to the
        // handler function
        responseXmlHandler(req.responseXML);
       alert(req.responseXML);

      }

it doesn't show me that alert .. !!

Should be
    writeSN(req.responseXML)
instead of
    responseXmlHandler(req.responseXML);
function getSN(itemModel) {

 var req = newXMLHttpRequest();

 req.onreadystatechange = getReadyStateHandler(req, writeSN); <---- This will be passed
 
 req.open("POST", "cart.do", true);
 
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 
req.send("itemModel="+itemModel);

}

function getReadyStateHandler(req, responseXmlHandler) {

  // Return an anonymous function that listens to the
  // XMLHttpRequest instance
  return function () {

    // If the request's status is "complete"
    if (req.readyState == 4) {
     
      // Check that a successful server response was received
      if (req.status == 200) {

        // Pass the XML payload of the response to the
        // handler function
       
         responseXmlHandler(req.responseXML);
       

      } else {

        // An HTTP problem has occurred
        alert("HTTP error: "+req.status);
      }
    }
  }
}


?
writeSN()  is a function, you only can pass object or value as paramater into the function.
Try change to

req.onreadystatechange = getReadyStateHandler(req);

getReadyStateHandler(req) {
         ....

        // Pass the XML payload of the response to the
        // handler function
       
         writeSN(req.responseXML);

         ....
}

It doesn't work ..

Here is my code:


index.jsp :

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="ajax1.js"></script>
<script type="text/javascript" language="javascript" src="cart.js"></script>

</head>

<body>

<form name = "ItemsForm" method="POST" action="cart.do">
      
<p>Item Model :<select size="1" name="itemModel" onchange= "getSN(this.options[this.selectedIndex].value)" >
 
      <option name ="itemModel" value="HP500">Hp500</option>
      <option name ="itemModel" value="HP600">Hp600</option>
      <option name ="itemModel" value="HP700">Hp700</option>
      </select></p>
       
      <p>Item Serial Number : <select size="1" name="ItemSN" id ="dropdown2"></select></p>
      
       
      
<p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>

<ul id="cart-contents">

 
</ul>

</body>

</html>

--------------------------------

My ajax1 javaScript:

/*
 * Returns an new XMLHttpRequest object, or false if the browser
 * doesn't support it
 */
function newXMLHttpRequest() {

  var xmlreq = false;

  // Create XMLHttpRequest object in non-Microsoft browsers
  if (window.XMLHttpRequest) {
    xmlreq = new XMLHttpRequest();

  } else if (window.ActiveXObject) {

    try {
      // Try to create XMLHttpRequest in later versions
      // of Internet Explorer

      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
     
    } catch (e1) {

      // Failed to create required ActiveXObject
     
      try {
        // Try version supported by older versions
        // of Internet Explorer
     
        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");

      } catch (e2) {

        // Unable to create an XMLHttpRequest by any means
        xmlreq = false;
      }
    }
  }

return xmlreq;
}


function getReadyStateHandler(req) {

  // Return an anonymous function that listens to the
  // XMLHttpRequest instance
  return function () {

    // If the request's status is "complete"
    if (req.readyState == 4) {
     
      // Check that a successful server response was received
      if (req.status == 200) {

        // Pass the XML payload of the response to the
        // handler function
       
         writeSN(req.responseXML);
       

      } else {

        // An HTTP problem has occurred
        alert("HTTP error: "+req.status);
      }
    }
  }
}


--------------------------------

My cart javaScript:

function getSN(itemModel) {

 var req = newXMLHttpRequest();

 req.onreadystatechange = getReadyStateHandler(req);
 
 req.open("POST", "cart.do", true);
 
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 
req.send("itemModel="+itemModel);

}


function writeSN(snXML){

var result = snXML;

array2 = result.split("#");

var dropdown = document.getElementById("dropdown2");

for ( var I = 0 ; I < array2.length ; I++){

dropdown.options.add(new Option(array2[I],array2[I]));

}

--------------------------------------------

My Servlet code:

public void doPost(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
       
       
        String itemModel = req.getParameter("itemModel");
       
        System.out.println("---------- this is the model---------: "+itemModel);
       
        Vector result = getAllSN(itemModel);
       
        String snXML = toXML(result);
       
        System.out.println("This is:-----------------------------------"+snXML);
       
        res.setContentType("application/xml");
       
        res.getWriter().write(snXML);
       
        res.getWriter().close();
       
         System.out.println("------ the response----"+res.isCommitted());
       
       
       
       
       
       
    }

-------------------------------------

How I make sure that I have received my response? is there any system.print.out in javaScript ?..=)


try add in alert in javascript. Is there any javascript error show on browser?

function writeSN(snXML){
   alert(snXML);
   ...
}
alert(SNXML) == gives me this message: [Object]

Is there any javascript error show on browser? <= show me in the status bar (Errors on page)
in the servlet change the content type as text/html and also u change the browser setting of IE to enable script debugging. Follow these steps to change the setting
1) open IE
2) select tools->Internet Options
3) select Advance tab in the dialog box
4) see whether "Disable Script Debugging (Internet Explorer" and "Disable script        
     Debugging(Other)" is unchecked
5) and also check the below option "Display a notification about every script error"
6) click ok and open the page in IE

Then will get the error message and see the details and send me the error message

it gives me this messgae:

object doesn't support this property or method
in which line its giving the error and also send me those few line above and below that
the eroor in line 22 :

function writeSN(snXML){

alert(snXML)

var result = snXML;

array2 = result.split("#"); //<----------------22( in this line)

var dropdown = document.getElementById("dropdown2");

for ( var I = 0 ; I < array2.length ; I++){

dropdown.options.add(new Option(array2[I],array2[I]));

}

}

and I got the following message whn I debug the error .. " Script does not support disassembly."

when I run in the firefox , alert message is : null
see what type of object is snXML i dont think its a string object its some other... just check that one

see this one writeSN(req.responseXML); what is this and what is responseXML
uses some other functions on snXML object and see whether its working

substring()
charAt()
split () and join()
toUpperCase()
toLowerCase()
first I declare the req as the following:
 
var req = newXMLHttpRequest();

then pass the response of the req (When it is completed) to writeSN(req.responseXML):

 req.onreadystatechange = getReadyStateHandler(req,writeSN);

f (req.status == 200) {

        writeSN(req.responseXML);
}


function writeSN(snxml){} // for extract the data

I have follow the listings in this link : http://www-128.ibm.com/developerworks/library/j-ajax1/
it doen't work . I think it receive null response ?! :((
instead of using req.reponseXML use req.responseText... since responseXML is not a String object its a Document object
so try this one

for reference see this link
http://www.brainjar.com/dhtml/ajax/
Thank u .. I will read them and try to know what is the problem .. =)
ASKER CERTIFIED SOLUTION
Avatar of deeppra
deeppra

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
woow . It display the Item serial number in the alter message .. but it doesn't spilt them.

after alerting the serial number it shows me an error message .. ?
send me the code after the alert message and send me the error message and line number
look at this http://www.4img.com/ar/up/06/11/22/d814f4e3dcf9e6f473e213232b9ba115.jpg

function writeSN(snXML){

var result = snXML;

alert(snXML);

array2 = result.spilt("#");

var dropdown = document.getElementById("dropdown2");

for ( var I = 0 ; I < array2.length ; I++){


dropdown.options.add(new Option(array2[I],array2[I]));

}
}

this is my display html:

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="ajax1.js"></script>
<script type="text/javascript" language="javascript" src="cart.js"></script>

</head>

<body>

<form name = "ItemsForm" method="POST" action="cart.do">
      
<p>Item Model :<select size="1" name="itemModel" onchange= "getSN(this.options[this.selectedIndex].value)" >
 
      <option name ="itemModel" value="HP500">Hp500</option>
      <option name ="itemModel" value="HP600">Hp600</option>
      <option name ="itemModel" value="HP700">Hp700</option>
      </select></p>
       
      <p>Item Serial Number : <select size="1" name="ItemSN" id ="dropdown2"></select></p>
      
       
      
<p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>



 
</ul>

</body>

</html>
send me the detail error message and send me the line number
okay fine which line is 23
line 23
char1

Error: object doesn't support thie property or method

code:0
it works thank u .. it was spelling mistake

array2 = result.spilt("#"); <--- here it should be array2 = result.split("#");

Thank u .. u deserve the points
okay fine.... Thanks