Load HTML file from drop-down created from XML file

Posted By: Ian on Jan 30, 2015 in JavaScript, Snippets

Question

How can i now load the HTML file selected from the Dynamically created drop-down.

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" id="soups">';
    str += '<option value="">Select a soup</option>';

    /* 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;
    /* when dom ready and select changes run script */
    window.onload = function() {
            if (window.addEventListener) {
                document.getElementById('soups').addEventListener('change', loadRecipe, false);
            } else if (window.attachEvent) {
                document.getElementById('soups').attachEvent("onchange", loadRecipe);
            }
            /* get value of selected soup and insert it into the page using object data */
            function loadRecipe() {
                var x = document.getElementById("soups").value;
                document.getElementById("showRecipe").innerHTML = '<object data="' + x + '" type="text/html" width="500" height="700"></object>';
            }
        }
</script>

Demo xml-select-html.php

AnonymousIan.J.Gough

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,
Ian.J.Gough

protected by copyscape duplicate content check

Categories


Powered by Banner Bar 125