Reputation: 789
I am trying to create a simple html5 page, that when the page loads, a Select HTML5 object will be populated with a list of values that are stored in an XML and called using an external javascript file.
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript" charset="utf-8"></script>
</head>
<body onLoad="javascript:loadXML()">
<header>
<h1></h1>
</header>
<form name="myForm" method="GET" action="">
<select id="cbLDAP"></select>
</form>
</div>
</body>
</html>
JS:
// variables declaration
var XML_PATH = "XML/ou.xml";
var select = $('#cdLDAP');
// load XML file
function loadXML()
{
$.ajax({
type: "GET",
url: XML_PATH,
dataType: "xml",
success: function(xml)
{
$(xml).find('LDAP').each(function()
{
var ou = $(this).find('OU').text();
select.append("<option/><option class='ddheader'>"+ou+"</option>");
});
$(this).find('Name').each(function(){
var name = $(this).text();
select.append("<option class='ddindent' value='"+ name +"'>"+name+"</option>");
});
}
});
}
XML:
<?xml version= "1.0" encoding="UTF-8"?>
<DropDown>
<LDAP>
<OU>1</OU>
<OU>2</OU>
<OU>3</OU>
<OU>4</OU>
<OU>5</OU>
<OU>6</OU>
</LDAP>
</DropDown>
When I load my html file in Firefox 11, the Select object is not populated. What am I doing wrong? Thank you.
Upvotes: 1
Views: 7214
Reputation: 2899
You had a typo between the SELECT element's ID and the jQuery appending code. Also, you were iterating through the parent node that had not text values, as opposed to the child "OU" nodes.
Here's some example code that fixes the XML parsing and cleans up some incorrectly named element IDs:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" charset="utf-8"></script>
</head>
<body>
<header>
<h1></h1>
</header>
<form name="myForm" method="GET" action="">
<select id="cdLDAP">
<option/>
</select>
</form>
</div>
<script type="text/javascript">
// variables declaration
var XML_PATH = "XML/ou.xml";
// load XML file
$(function() {
$.ajax({
type: "GET",
url: XML_PATH,
dataType: "xml",
success: function(xml) {
$(xml).find('LDAP').find('OU').each(function(i) {
var ou = $(this).text();
$('#cdLDAP').append("<option class='ddheader'>"+ou+"</option>");
});
$(this).find('Name').each(function() {
var name = $(this).text();
$('#cdLDAP').append("<option class='ddindent' value='"+ name +"'>"+name+"</option>");
});
}
});
});
</script>
</body>
</html>
Lastly, its worth noting that the onLoad action and wrapping the parsing code in a function isn't really necessary with jQuery; and don't forget to place the client-side code on the same server as the XML file, otherwise you will run into the same-origin policy blocking the AJAX fetch of the XML data.
Upvotes: 1