Reputation: 1665
I have a select element where a user can add and remove options. When the user is done they will then click save but I cannot figure out how to then get all the options from the select. I have found JQuery to get all the selected but I just need all of them. I tried this:
var str = "";
$("#wordList").each(function () {
str += $(this).text() + ",";
});
alert(str);
But it just concatenates all the option to one long string that ends in a comma.
Upvotes: 2
Views: 12981
Reputation: 268324
Just map the options to an array of their values:
var options = $("select option").map(function () {
return $(this).text();
}).get();
At this point you have an array. If you want it to be a CSV, use the join
method:
options.join(",");
The end result is either an array ["One", "Two"]
or a string "one,two"
.
Upvotes: 7
Reputation: 1893
That code does exactly what it says on the box. Normally I would expect you would have used $("#wordList option")
to get the options. I am guessing that if the options are "This", "That" and "The other" then you got ThisThatThe Other,
, which is what that code will do (that is all the text inside the #wordList element, which essentially includes all the options inside that element. The array you are performing .each()
on has a single element: "ThisThatThe Other", you iterate over it once and add a comma).
You want to concatenate the text of each of the OPTIONS in #wordList (I think), so try
var str = "";
$("#wordList option").each(function () {
str += $(this).text() + ",";
});
alert(str);
to give you a string of all the words (like This,That,The Other,
)
If you want an array, instead do this:
var arr = [];
$("#wordList option").each(function () {
arr.push($(this).text());
});
alert(arr.join(", "));
Upvotes: 5
Reputation: 43718
"it doesn't matter if I get it in an array or csv, I just need to get all the option elements from the select element"
$('#your_select_id').prop('options')
will return you a collection of all the options.
You can then do whatever you want with it... here's an example where we collect all option values in an array.
var values = [];
$.each($('#your_select_id').prop('options'), function () {
values.push(this.value);
});
Upvotes: 3