I have a select box.
<select id='x'>
<option value='1'>'Vineet'</option>
<option value='2'>'Vivek'</option>
<option value='3'>'Madhu'</option>
</select>
The options are added dynamically to it. At the end, I want to collect the values of ALL option elements contained within this select box into an array. I searched the forum for the answer, but Q/A are there for getting the 'selected' option only.
I tried this:
var myList = [];
$('#x').each(function() { myList.push( $(this).value() ) });
In firebug, It gives this error:
missing } after property list
But I fail to see any missing }
. What am I doing wrong here?
You need to loop through each option
element within the select, not just the select itself, also, the correct method to get the value of an input in jQuery is val()
, try this:
myList = [];
$('#x option').each(function() {
myList.push($(this).val())
});
Example fiddle
You can also use map()
:
var myList = $('#x option').map(function() {
return this.value;
}).get();
// A version of the above in ES6 (note: unsupported in IE)
let myList = $('#x option').map((i, el) => el.value).get();
In all the above cases the myList
variable will contain an array of strings.
Try jQuery function for getting the value of an element (wrapped in a jQuery object) is .val()
, not .value()
- that may be causing some confusion, though I can't be sure.
As a side note, your selector is incorrect for what you want. $('#x')
will return all of the elements that have an id
of x
- which should only ever be one element - then the .each()
will iterate over that set of elements (so it will call the function once). You'll just end up with an array that contains a single value, which will be the currently selected value of the <select>
input.
Instead, use $('#x > option')
which will return all <option>
elements that are immediate children of the <select>
element with the id
of x
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With