user9240475
user9240475

Reputation:

How to get the text of all options in a select input field

How can I get all the text content of all options comma separated using jQuery? The value of the select field itself is only the value of the currently selected option.

const foo = $('#selector').val()
document.write(foo)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selector" id="selector">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>

I want something like this as a result

Option 1, Option 2,Option 3

Upvotes: 3

Views: 599

Answers (4)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can follow simple logic:

  1. Loop over the <option>element
  2. Get the text from each <option>element and push it to an array.
  3. Stringify the array with toString() and get the values as comma separated.

var optionsArray = [];
//loop over each option element
var optionElements = $('#selector option').each(function() {
  //push the text of option in the array
  optionsArray.push($(this).text());
}); 
//stringify the array to get the comma seperated result
console.log(optionsArray.toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selector" id="selector">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
 <option value="3">Option 3</option>
</select>

Upvotes: 0

Francis Leigh
Francis Leigh

Reputation: 1960

let arr = []
$('select > option').each((i, {innerHTML}) => arr.push(innerHTML))

console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selector" id="selector">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>

Here i have queried the options of the select which gave me an array of elements. I looped through those elements and pushed their respective innerHTML to an arr.

Use Array.prototype.join() to reduce that array to a string :-)

Upvotes: 0

Ele
Ele

Reputation: 33726

Execute each function over your options, push them into an array and then execute join function.

var collected = [];
var foo = $('#selector option').each(function() {
  collected.push($(this).text());
}); 

console.log(collected.join(','));
.as-console-wrapper {
  max-height: 100% !important
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selector" id="selector">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
 <option value="3">Option 3</option>
</select>

Upvotes: 3

void
void

Reputation: 36703

$("#selector option:selected").text();

Will give you selected text instead of the value.

Upvotes: -1

Related Questions