Using JQuery / AJAX to populate a drop-down menu with an XML file.

advertisements

I have a drop-down menu that I need to populate from an XML file. Here is the script I am trying to use:

 $(document).ready(function(){       // load jQuery 1.5
  function loadfail(){
  alert("Error: Failed to read file!");
 }

 function parse(document){
 $(document).find("menuItem").each(function(){
    var optionLabel = $(this).find('text').text();
    var optionValue = $(this).find('value').text();
    $('.opening').append(
   '<option value="'+ optionValue + '">' + optionLabel + '</option>'
    );
 });
 }

 $.ajax({
  url: 'http://ourwebserver/Online%20App/jobTitles.xml',    // name of file with our data - link has been renamed
  dataType: 'xml',    // type of file we will be reading
  success: parse,     // name of function to call when done reading file
  error: loadfail     // name of function to call when failed to read
 });
});

Here is a sample from the xml file:

<menu>
<menuItem>
    <value>612</value>
    <text>CLERK-CMH HOS HIM</text>
</menuItem>
<menuItem>
    <value>1632</value>
    <text>FAM PRACT-CMH CLN Southside Medical</text>
</menuItem>

And here is the html code that contains the drop down I am trying to populate:

 <strong>Position(s) Desired</strong>
             <select name="opening" size="5" multiple="multiple" id="opening">
      </select>

I'm not getting an error message, but I'm also not getting any data to populate in the menu.

I have also tried the code/solution at this link: populating a drop down menu with xml file and had a similar outcome, no errors, but no data.

Thanks in advance for your help.


You're using a class selector (.opening) rather than the ID (#opening) to find the <select> element. Using $('#opening') in your parse function should work as expected.