str +="<select id='student_id' onchange=get_details()>";
Inside this function we will first read the selected student id of the listbox by using getElementById().
var student_id=document.getElementById('student_id').value;
We know how to display all the element of the xml file. We will use one if command to get the matching student record by equating it will looping value of variable i.
for(i=0;i<x.length;i++){
if(y[i].childNodes[0].nodeValue ==student_id){
str1 = str1 +' id = ' + student_id ;
str1 = str1 + ' , Name : ' + x[i].childNodes[0].nodeValue ;
str1 = str1 + ' , Class : ' + z[i].childNodes[0].nodeValue ;
} // end of if
} // end of for loop
Then we will display all the other details of the matching student id.
We have used our sample xml file
Demo of displaying dropdown list box in xml
Here is the script.<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>demo</title>
</head>
<body>
<script type="text/javascript">
function get_details(){
var student_id=document.getElementById('student_id').value;
var z=xml_str.getElementsByTagName("class");
str1='';
for(i=0;i<x.length;i++){
if(y[i].childNodes[0].nodeValue ==student_id){
str1 = str1 +' id = ' + student_id ;
str1 = str1 + ' , Name : ' + x[i].childNodes[0].nodeValue ;
str1 = str1 + ' , Class : ' + z[i].childNodes[0].nodeValue ;
} // end of if
} // end of for loop
document.getElementById('disp').innerHTML=str1;
//alert(str1);
}
if (window.XMLHttpRequest)
{ my_xml=new XMLHttpRequest();
}
else
{
my_xml=new ActiveXObject("Microsoft.XMLHTTP");
}
/////////////////////////////
my_xml.open("GET",'../php_tutorial/file-xml-demo.xml',false);
my_xml.send();
xml_str=my_xml.responseXML;
var x=xml_str.getElementsByTagName("name");
var y=xml_str.getElementsByTagName("id");
var str="";
str +="<select id='student_id' onchange=get_details()>";
for(i=0;i<x.length;i++){
str +='<option value=' + y[i].childNodes[0].nodeValue + '>' + x[i].childNodes[0].nodeValue + '</option>';
}
str +='</select>';
document.write(str);
</script>
<div id='disp'></div>
</body>
</html>
Dropdown listbox in XML