1

I've been trying to get the values in a multiple select box and put it in an array. I've tried this:

JQUERY

var selectedValues = $('#multipleSelect').val();

HTML

<select id="multipleSelect" multiple="multiple">
    <option value="1">Text 1</option>
    <option value="2">Text 2</option>
    <option value="3">Text 3</option>
</select>

By Darin Dimitrov from this SO question.

I was wondering if there was a way to get all the values in the multiple select box without having to select anything.

Maistrenko Vitalii
  • 994
  • 1
  • 8
  • 16
Mel
  • 111
  • 1
  • 12

2 Answers2

3

Try this:

$('#multipleSelect option').each(function() {
    var value = $(this).attr(‘value’);
    // push the value to an array
});
hungersoft
  • 531
  • 4
  • 8
3

One option is to map and get the values

var values = $("#multipleSelect option").map(function(){return this.value}).get();

//console.log( values );
alert( values );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="multipleSelect" multiple="multiple">
   <option value="1">Text 1</option>
   <option value="2">Text 2</option>
   <option value="3">Text 3</option>
</select>
Eddie
  • 26,593
  • 6
  • 36
  • 58
  • this is what I need. uhm, how i can display the values in say an alert box? i cant for the life of me figure out – Mel Mar 22 '18 at 03:03
  • @Mel, you can just use `alert()`. I updated the example. But it is better to use `console.log` for debugging. – Eddie Mar 22 '18 at 03:04
  • What id are you using on your `multiple` html @Mel ? – Eddie Mar 22 '18 at 09:00
  • I'm using `call_Prod` as an id. I did change the `#multipleSelect` to that when I tried but I get an empty alert box – Mel Mar 22 '18 at 09:17
  • Can you create a jsfiddle.com of your code? If it is not working, it means that there is something wrong with the your implementation. The code above should work. @Mel – Eddie Mar 22 '18 at 09:23
  • I figured it was something I was doing wrong. Thank you for bearing with me. The jsfiddle is here: https://jsfiddle.net/cn4c8nsx/13/ – Mel Mar 22 '18 at 09:42
  • @Mel I think the issue was, you are running the code before all the html code was loaded. Why don't you use `jQuery` event listener instead of `onclick` – Eddie Mar 22 '18 at 09:48