Search code examples
javascriptdrop-down-menuselectedindex

Javascript selectedIndex is returning undefined on a HTML drop-down menu


Currently I am trying to write a method that appends the value of a dropdown menu to an html link. However I an having trouble retrieving the text of the selection from the menu. I narrowed the problem down to the selectedIndex method in Javascript. It returns undefined. I've included my method below.

function getSize(productID){
    var sizeBox = document.getElementsByName(productID);
    alert(document.getElementsByName(productID).selectedIndex);
    var sizeSelected = sizeBox.options[sizeBox.selectedIndex].text;
    alert(sizeSelected);
    var link = document.getElementById(productID).getAttribute("href");
    link = link + "&size=" + sizeSelected;
    document.getElementById(productID).setAttribute("href",link);
    return true;
}

Solution

  • getElementsByName returns an HTMLCollection. You should say: getElementsByName[0]