0

HTML:

<select multiple="" name="selectinputmultiple" id="">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

jQuery:

$('select[name=selectinputmultiple]').on('change', function() {
    console.log(this.value);
});

Console just shows the first selected value, I want to save values in an array on each change. So for example:

  • If a user selected 1 and 2 => {1,2}
  • Then the user unselected 1 and selected 3 => {2,3}
eozzy
  • 66,048
  • 104
  • 272
  • 428

5 Answers5

2

Use map() to get the all selected values in array

$('select[name=selectinputmultiple]').on('change', function () {  
    var val=$('select[name=selectinputmultiple] option:selected').map(function () {
            return this.value;
    }).get();
    console.log(val)
});

DEMO

Balachandran
  • 9,567
  • 1
  • 16
  • 26
1

You can use .val() which should give an array

$('select[name=selectinputmultiple]').on('change', function() {
  $('#log').html(JSON.stringify($(this).val()))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select multiple="" name="selectinputmultiple" id="">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>
<div id="log"></div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

As per .val() doc

In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.

You can simply use:

var values = $('[name="selectinputmultiple"]').val();
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
-1

This should deinately work,

 $('select[name=selectinputmultiple]').on('change', function() {
   $('select[name=selectinputmultiple]').each(function() {
     console.log($(this).val());
     alert($(this).val());
   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select multiple="" name="selectinputmultiple" id="">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>
Dimag Kharab
  • 4,439
  • 1
  • 24
  • 45
-1

Try this:

<select multiple="" name="selectinputmultiple" id="">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

$('select[name=selectinputmultiple]').on('change', function() {
    $('select[name=selectinputmultiple]').each(function() {
       console.log($(this).val());
     });  
});

Look at this JSFiddle

Captain Planet
  • 408
  • 3
  • 19