Mel
Mel

Reputation: 111

Get values in multiple select

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.

Upvotes: 1

Views: 85

Answers (2)

hungersoft
hungersoft

Reputation: 531

Try this:

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

Upvotes: 3

Eddie
Eddie

Reputation: 26844

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>

Upvotes: 3

Related Questions