Reputation:
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
Reputation: 30739
You can follow simple logic:
<option>
element<option>
element and push it to an array.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
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
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
Reputation: 36703
$("#selector option:selected").text();
Will give you selected text instead of the value.
Upvotes: -1