I was recently asked how to extract values from an HTML dropdown. Here’s the code an due credit.
Option 1 – only works with traditional ways dropdowns are defined.
var ddlArray= new Array(); var ddl = document.getElementById('PLACEHOLDER_NAME_OF_SELECT_FORM'); for (i = 0; i < ddl.options.length; i++) { ddlArray[i] = ddl.options[i].value; console.log(ddlArray[i]+','); }
Option #2 – is more flexible when dropdowns are custom and don’t use the traditional select,option HTML elements.
var ddlArray= new Array(); var printValue=""; var ddl = document.querySelectorAll("#cars > option"); for (i = 0; i < ddl.length; i++) { printValue=printValue + ddl[i].innerText+','; } console.log(printValue);
<!--Example HTML to test out code --> <select id="cars" name="carlist" form="carform"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select>
Code from – https://stackoverflow.com/questions/6378680/get-all-the-values-of-a-dropdownlist-to-an-array-using-javascript