Search code examples
javascriptarrayswordpresshyperlinkdropdownbox

Creating a dropdown list with hyperlinked items in an array


I'm very new to JS, so forgive the simplicity of this question... Trying to create a dropdown list with hyperlinked items using an array. The end product will have hundreds of entries, so it's important to save space.

Two things to keep in mind: I can't use JQuery and I have to integrate this in WordPress.

I know I'm doing this incorrectly, but the below code should give an accurate idea of what I'm trying to do. Any help much appreciated.

<body>
<form id="siteList">
  <select id="selectSite">
  <option>Choose a site</option>
  </select>
</form>
</body>

</script>
var myArray = new Array("Google", "Yahoo", "Bing", "Gmail", "Facebook");

var links = new Array("http://www.google.com", "http://www.yahoo.com", "http://www.bing.com", "http://www.gmail.com", "http://www.facebook.com");

// Get dropdown element from DOM
var dropdown = document.getElementById("selectSite")

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i].link(links[i]), myArray[i].link(links[i]));
}
</script>

http://jsfiddle.net/L2awjmvd/


Solution

  • You have to write the code like below:

    <script type="text/javascript">
        function createarray() {
            var myArray = new Array("Google", "Yahoo", "Bing", "Gmail", "Facebook");
            var links = new Array("http://www.google.com", "http://www.yahoo.com", "http://www.bing.com", "http://www.gmail.com", "http://www.facebook.com");
            var dropdown = document.getElementById("selectSite");
    
            for (var i = 0; i < myArray.length; ++i) {
                var option = document.createElement("option");
                option.text = myArray[i];
                option.value = links[i];
                dropdown.add(option);
    //          dropdown[dropdown.length] = new Option(myArray[i].link(links[i]), myArray[i].link(links[i]));
            }
        }
    
        function selectSiteRedirect(selectedSite) {
            window.location.href = selectedSite;
        }
    </script>
    <body onload="createarray();">
        <form id="siteList">
            <select id="selectSite" onchange="selectSiteRedirect(this.value);">
                <option>Choose a site</option>
            </select>
        </form>
    </body>