Tuesday, 13 January 2015

Populate drop-down list from XML

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

Answer
<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); // 
    xhr.send();
    /* 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;
</script>


Demo xml-select-tag.php

No comments:

Post a Comment