I have an XML file, and each element has a child called category. On my HTML page, I have created a dropdown form that lists the possible categories (as well as “all”). When the user selects a category from the dropdown list, it assigns a javascript variable corresponding to that category, and I then use javascript/ajax to iterate over the XML file and display a list of the elements with that category. That is all working correctly… but when it displays the list, instead of showing it under the dropdown, the dropdown goes away entirely and all you see is the list. I want to display the list BELOW the dropdown, so that the user can select a different category if he/she chooses. Please help me figure out why it’s getting rid of the dropdown and how to fix it. Thanks in advance! (And also, apologies if this is a really dumb question… I’m very new to javascript.)
<html>
<head>
<script>
//This is the basic XML stuff.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","websites.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("site");
//This is the part that handles printing the items under the various categories.
function printCat(cat)
{
if(cat=="all")
{
for (i=0;i<x.length;i++)
{
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br/>");
}
}
else
{
for (i=0;i<x.length;i++)
{
if (x[i].getElementsByTagName("category")[0].childNodes[0].nodeValue==cat)
{
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br/>");
}
}
}
}
</script>
</head>
<body>
<form action='../'>
<select onchange='printCat(this.options[this.selectedIndex].value)'>
<option value='all'>All</option>
<option value='search'>Search</option>
<option value='social_media'>Social Media</option>
</select>
</form>
</body>
</html>
Instead of document.write, use the loop you have to create a string of site names (or whatever). Include the newline character after each one ie: + “\n” +
At the end of the function add the line: this.innerHTML = myString;
The “this” refers to the functions calling element and the “innerHTML” refers to the space that sits between the calling elements open & close tags. It will overwrite anything else sitting there (much like document.write will overwrite everything between the doc tags). From there fine tune to get the result you want.
For example, create the second dropdown element and call the function from that element.