44

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?

isherwood
  • 58,414
  • 16
  • 114
  • 157
dan.m.kumar
  • 758
  • 2
  • 9
  • 20

7 Answers7

44

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/

Abraham P
  • 15,029
  • 13
  • 58
  • 126
14

example:

<select name="sel1" id="sel1">
    <option value="001">option 001</option>
    <option value="002">option 002</option>
    <option value="003">option 003</option>
    <option value="004">option 004</option>
</select>

values:

let selectElement = document.querySelectorAll('[name=sel1]');
let optionValues = [...selectElement[0].options].map(o => o.value)

option text

let selectElement = document.querySelectorAll('[name=sel1]');
let optionNames = [...selectElement[0].options].map(o => o.text)
Marek Lisiecki
  • 498
  • 6
  • 10
  • [].slice.call(selectElement[0].options).map(o => o.value); also works. Not sure whether this or the ellipsis method is better. – kloddant Aug 16 '22 at 17:09
8

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 "

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
6

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 + ",";
      }
gar
  • 14,152
  • 5
  • 30
  • 31
Dorjee Karma
  • 339
  • 2
  • 5
4

Base on @Marek Lisiecki, I made a demo for answer this question as below.

I think this is better way that using ES6

function displayResult(){
  let selectElement = document.getElementById('mySelect');
  let optionNames = [...selectElement.options].map(o => o.text);
  console.log(optionNames);
}

function displayResult(){
  let selectElement = document.getElementById('mySelect');
  let optionNames = [...selectElement.options].map(o => o.text);
  console.log(optionNames);
}
<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>
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
2

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);
}
Fuzzley
  • 306
  • 2
  • 8
0

Solution

Building on Marek's answer, the most easy-to-understand way would probably be to use the following.

function displayResult(){
  let optionNames = Array.from(document.getElementById('mySelect').options).map(option => option.text);
  console.log(optionNames);
}

Explanation

First, using document.getElementById('mySelect'), we obtain the select element .

Then, using .options, we obtain an HTMLOptionsCollection object containing all of the options.

Then, using Array.from(), we obtain an array object containing all of the options.

Finally, using .map(option => option.text), we create a new array the display texts of all of the options.

In the final step, we use the map() method to create a new array with the the display texts of the options from the array of the options. The method iterates over all of the elements (HTMLoptions) in the array of options and executes the provided function (option => option.text) for each array element. The map() method is similar to the forEach() method as it also iterates over all of the elements in the given array. However, the map() method also saves the results obtained the provided function into a newly created array. The provided function is an arrow function, which takes the argument option (which is an HTMLoption element from the array of options) and returns the display text of the option (option.text).

Code snippet

function displayResult(){
  let optionNames = Array.from(document.getElementById('mySelect').options).map(option => option.text)
  console.log(optionNames);
}
<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>
Jakub Holan
  • 303
  • 1
  • 8