user1765862
user1765862

Reputation: 14155

store selection from multiselect element inside string

I have multiple select box like

<select id="myMultiSelect" class="multiselect form-control" name="Status" multiple="multiple">
   <option value="AA">AA option</option>
   <option value="BB">BB option</option>  
     ...
  <option value="FF">FF option</option>  


</select>

How can I usig jquery store selected values inside string separated with comma like

var string = "AA,BB,CC";

Upvotes: 1

Views: 59

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34186

Simply assign it to variable. The .val() returns an array of values:

var myval = $('select#myMultiSelect').val();

Here is a sample fiddle to show it working: http://jsfiddle.net/MarkSchultheiss/6jyrfcfo/

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 241038

You could use the .map() method to get the array of values and then join them:

Example Here

var selectValueString = $('#myMultiSelect > option').map(function () {
    return this.value;
}).get().join(',');

console.log(selectValueString); // "AA,BB,FF"

Alternatively, without jQuery:

Example Here

var options = document.querySelectorAll('#myMultiSelect > option');
var selectValueString = Array.prototype.map.call(options, function(el){
    return el.value;
}).join(',');

console.log(selectValueString); // "AA,BB,FF"

Upvotes: 4

Related Questions