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

7

50

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?

Ailurophobe answered 7/8, 2013 at 20:46 Comment(0)
O
50

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;

JSFiddle

Obtrude answered 7/8, 2013 at 20:50 Comment(0)
N
23

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.querySelector('[name=sel1]');
let optionValues = [...selectElement.options].map(o => o.value)

option text

let selectElement = document.querySelector('[name=sel1]');
let optionNames = [...selectElement.options].map(o => o.text)

const getValues = () => {
  let selectElement = document.querySelector('[name=sel1]');
  let optionValues = [...selectElement.options].map(o => o.value);
  console.log({optionValues});
}

const getOptionText = () => {
  let selectElement = document.querySelector('[name=sel1]');
  let optionNames = [...selectElement.options].map(o => o.text);
  console.log({optionNames});
}
* {
  font-family: 'jetBrains Mono',monospace;
}

select, button {
  padding: 5px 20px;
}
form {
  margin-bottom: 20px;
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono&display=swap" rel="stylesheet">

<form>
    <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>
    <button type="button" onclick="getValues()">GET VALUES</button>
    <button type="button" onclick="getOptionText()">GET OPTION TEXT</button>
</form>
Nonnah answered 18/4, 2021 at 22:56 Comment(2)
[].slice.call(selectElement[0].options).map(o => o.value); also works. Not sure whether this or the ellipsis method is better.Sinistrad
Use querySelector instead of querySelectorAll. This way you don't need [0]Hypogeal
L
9

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 "

Livorno answered 7/8, 2013 at 20:52 Comment(0)
L
8

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 + ",";
      }
Lemoine answered 2/10, 2013 at 5:0 Comment(0)
E
5

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>
Engagement answered 23/9, 2021 at 2:5 Comment(0)
T
3

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>
Tearle answered 2/6, 2023 at 12:42 Comment(0)
M
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);
}
Mannes answered 7/8, 2013 at 20:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.