Populate drop-down list from XML

Posted By: Ian on Jan 29, 2015 in JavaScript, Snippets, XML

So now i have what i want how can i put that into a select tag?


<script type="text/javascript">
    /* check browser supports XMLHttpRequest object and create one else create ActiveXObject */
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    /* create an instance of the XMLHttpRequest object, open a URL, and send the request. */
    xhr.open("GET", 'soups/soups.xml', false); // 
    /* get the response of the request (sent as string) */
    xhrStr = xhr.responseXML;
    /* get required elements */
    var xhrTitle = xhrStr.getElementsByTagName("title");
    var xhrFilename = xhrStr.getElementsByTagName("filename");
    /* add select tag to variable */
    var str = '<select name="Soups">';
    /* loop through all title tags (will get filename tags found between title tags) */
    for (i = 0; i < xhrTitle.length; i++) {
        /* with the values we get add them to option tag each time we run through the loop */
        str += '<option value=' + xhrFilename[i].childNodes[0].nodeValue + '>' + xhrTitle[i].childNodes[0].nodeValue + '</option>';
    /* close select */
    str += '</select>';
    /* put select element inside createSelect */
    document.getElementById("createSelect").innerHTML = str;

Demo xml-select-tag.php


Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,

protected by copyscape duplicate content check


Powered by Banner Bar 125