Alexandre Rivara Alexandre Rivara - 1 year ago 43
jQuery Question

Jquery group result of a selector in an array of array

I have a random number of

select multiple
on my web page and when the user click on the send button, I retrieve the value of those
select multiple
through their
class
. I also use the chosen plug-in but I don't think it interfere with the issue I about to expose. Here is what my code looks like :

<select multiple="multiple" id="idName0" class="idName chosenSelect">
<option value="...">...</option>...
</select>
<select multiple="multiple" id="idName1" class="idName chosenSelect">
<option value="...">...</option>...
</select>


And to get the results :

results.push($(".idName").map(function(){return $(this).val();}).get());


Let's say I have 2
option
's selected in the first
select
(with the
value
foo and bar) and one in the second one (with the
value
foobar). All this give me an
array
looking like :

[foo,bar,foobar]


What I want is :

[[foo,bar],[foobar]]


From what I know, when you call .val() on selector pointing to a
select multiple
in give you an array with the different selected
option
's. And here, with multiple
select multiple
in the fray, I was hoping to create an array of those array.

Any help is welcomed.

Answer Source

You can use map() for this but you also need to wrap value of each select in array. If you don't want null's in array for empty selects you can add .filter(Boolean) after .get()

$('select').change(function() {
  var data = $("select").map(function() {
    return [$(this).val()]
  }).get()

  console.log(data)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" id="idName0" class="idName chosenSelect">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
<select multiple="multiple" id="idName1" class="idName chosenSelect">
  <option value="4">4</option>
</select>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download