Vineet
Vineet

Reputation: 624

jquery collect all option values from select box in a JSON array

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?

Upvotes: 8

Views: 18204

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 15

Anthony Grist
Anthony Grist

Reputation: 38345

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.

Upvotes: 1

Related Questions