thedj25
thedj25

Reputation: 13

Get all selected="selected" values and put into array

Trying to get all options with a selected="selected" attribute on a page.

There are many of these instances on the page but I can only seem to save the first to an array.

How the selected="selected" shows up:

<select bind-event-change="disableHiddenInputs()" bind="appliesToResource6" id="link_list_links__link_type" name="link_list[links][][link_type]">
<option value="frontpage">Store Frontpage</option>
<option selected="selected" value="collection">Collection</option>
<option value="product">Product</option>
<option value="catalog">All Products</option>
<option value="page">Page</option>
<option value="blog">Blog</option>
<option value="search">Search page</option>
<option value="http">Web Address</option>
</select>

What I have tried :

$('#link_list_links__link_type option:selected').map(function () {

return $(this).val();
});

It only returns the first selected="selected" option and not the rest of the iterations.

How do I return all of the options on the page with selected="selected"? What am I doing wrong?

Upvotes: 0

Views: 660

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388436

The problem is the id you have used, ID of an element must be unique, so when you use id-selector it will return only the first element with the said id. which means #link_list_links__link_type selects only 1 select element thus you are getting only one value.

A unique identifier for the element.
There must not be multiple elements in a document that have the same id value.

One solution here is to use a class to group similar elements so

<select bind-event-change="disableHiddenInputs()" bind="appliesToResource6"         name="link_list[links][][link_type]" class="link_list_links__link_type">

then

var array = $('.link_list_links__link_type option:selected').map(function () {
return $(this).val();
}).get();

Upvotes: 1

Related Questions