How can I get a list of all values in select box?


I am stumped. I have a form with a dropdown list, and I would like to grab a list of all the values in the list. I pulled the below example from w3 schools (yes, I know it's unreliable, but other solutions on stack overflow seem to be very similar to this). It was not working for me, and I tried plugging it into jsfiddle, but no luck.

<form>Select your favorite fruit:
    <select id="mySelect">
        <option value="a">Apple</option>
        <option value="o">Orange</option>
        <option value="p">Pineapple</option>
        <option value="b">Banana</option>
<button type="button" onclick="displayResult()">Display text of all options</button>


function displayResult() {
    var x = document.getElementById("mySelect");
    var txt = "All options: ";
    var i;
    for (i = 0; i < x.length; i++) {
        txt = txt + "\n" + x.options[i].value;

Not working on jsfiddle:

However, it works at their site:

Any ideas on how to solve this?

This question is tagged with javascript html forms selection

~ Asked on 2013-08-07 20:46:02

The Best Answer is


You had two problems:

1) The order in which you included the HTML. Try changing the dropdown from "onLoad" to "no wrap - head" in the JavaScript settings of your fiddle.

2) Your function prints the values. What you're actually after is the text

x.options[i].text; instead of x.options[i].value;

~ Answered on 2013-08-07 20:50:31






Link to fiddle

And I agree with Abraham - you might want to use text instead of value

The reason your fiddle didn't work was because you chose the option: "onLoad" instead of: "No wrap - in "

~ Answered on 2013-08-07 20:52:05

Most Viewed Questions: