[javascript] 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.

HTML:
<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>
    </select>
</form>
<button type="button" onclick="displayResult()">Display text of all options</button>

javascript:

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;
    }
    alert(txt);
}

Not working on jsfiddle: http://jsfiddle.net/WfBRr/1/

However, it works at their site: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_option_text2

Any ideas on how to solve this?

This question is related to javascript html forms selection

The 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;

http://jsfiddle.net/WfBRr/5/


It looks like placing the click event directly on the button is causing the problem. For some reason it can't find the function. Not sure why...

If you attach the event handler in the javascript, it does work however.

See it here: http://jsfiddle.net/WfBRr/7/

<button id="display-text" type="button">Display text of all options</button>

document.getElementById('display-text').onclick = function () {
    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;
    }
    alert(txt);
}

As per the DOM structure you can use below code:

var x = document.getElementById('mySelect');
     var txt = "";
     var val = "";
     for (var i = 0; i < x.length; i++) {
         txt +=x[i].text + ",";
         val +=x[i].value + ",";
      }

Change:

x.length

to:

x.options.length

Link to fiddle

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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to selection

Selection with .loc in python pandas: best way to select all columns whose names start with X UITableViewCell Selected Background Color on Multiple Selection Android RecyclerView addition & removal of items How can I get a list of all values in select box? Multiple select in Visual Studio? VBA: Selecting range by variables jQuery - select all text from a textarea How to select an item in a ListView programmatically? XPath: select text node