108

I have a multiple select:

<select name='strings' id="strings" multiple style="width:100px;">
    <option value="Test">Test</option>
    <option value="Prof">Prof</option>
    <option value="Live">Live</option>
    <option value="Off">Off</option>
    <option value="On">On</option>
</select>

I load data from my database. Then I have a string like this:

var values="Test,Prof,Off";

How can I set this Values in the multiple select? Already tried change the string in an array and put it as value in the multiple, but doesnt work...! Can someone help me with this? THANKS!!!

Zwen2012
  • 2,868
  • 7
  • 33
  • 56
  • all these examples just work for the hard-coded values given above, never work with real field values from the database. As soon as u replace values with database say for example : values = $('#').val();it does not work , it selects only the first value of the dropdown . And instead of giving the correct answer if I write the truth stack overflow deletes my view. – Zeldalink Apr 18 '21 at 02:43

8 Answers8

144

Iterate through the loop using the value in a dynamic selector that utilizes the attribute selector.

var values="Test,Prof,Off";
$.each(values.split(","), function(i,e){
    $("#strings option[value='" + e + "']").prop("selected", true);
});

Working Example http://jsfiddle.net/McddQ/1/

Kevin Bowersox
  • 88,138
  • 17
  • 142
  • 176
  • 1
    Thats cool, but how do you say that the selected vlaues should be selected in the "multiple select" with the id=string? – Zwen2012 May 16 '13 at 09:00
  • @user1824136 Excellent, Glad I could help someone this morning! – Kevin Bowersox May 16 '13 at 09:08
  • 2
    If we're going to depend on jQuery anyway, much prefer ŁukaszW.pl[`$('#strings').val(values.split(','))`](https://stackoverflow.com/a/21322784/1366033). Without jQuery, ŁukaszW.pl's Plain Old Javascript [`document.getElementById('strings').value = ["Test", "Prof", "Off"]`](https://stackoverflow.com/a/16583001/1366033) also accomplishes in a one-liner – KyleMit Jun 12 '18 at 22:46
124

in jQuery:

$("#strings").val(["Test", "Prof", "Off"]);

or in pure JavaScript:

var element = document.getElementById('strings');
var values = ["Test", "Prof", "Off"];
for (var i = 0; i < element.options.length; i++) {
    element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}

jQuery does significant abstraction here.

Adam Leggett
  • 2,797
  • 23
  • 21
ŁukaszW.pl
  • 9,244
  • 5
  • 34
  • 59
  • 1
    This worked perfect for me and my 'chosen' selects... have to add all the values at once (just like you say above) – Todd Vance Mar 17 '14 at 18:01
  • 4
    Hmm, the pure javascript isn't working for me on Chrome/mac or FF/mac. It has no effect on what's actually selected, at least what appears selected visually in the browser. – Bill Keese Apr 08 '14 at 08:20
  • 3
    Its working when I am passing string, but not when I am passing array. – Ravi G Sep 10 '14 at 15:19
  • Having the same issue; this only works with string values, not arrays (using plain JS, not jQuery). – jayp Sep 30 '16 at 07:18
  • I don't know why, but does not work for me :( It works in console but select list component isn't refreshed. (using bootsrap) – Muflix Mar 20 '17 at 14:58
  • 2
    For those experiencing issues with this, you should make sure you trigger a 'change' event after setting the value in JavaScript. Using jQuery this would be $("#strings").val(["Test", "Prof", "Off"]).trigger('change'); – Jon Wyatt Mar 29 '18 at 14:40
  • [this even works for checkboxes](http://jsfiddle.net/McddQ/2096/), the one function for everything. No idea why the answer to do it by hand is accepted – Hashbrown Nov 04 '18 at 07:13
  • @Hashbrown This answer claims that it can be done this way in pure JavaScript, but it cannot, the answer is incorrect on that point. This only works in pure JavaScript if the array has only one element on all browsers I tested. – Adam Leggett Nov 06 '18 at 00:14
  • It works, but you have to use If you don't put the attribute value, it will fail. – Martin Zvarík Nov 13 '19 at 19:54
22

Just provide the jQuery val function with an array of values:

var values = "Test,Prof,Off";
$('#strings').val(values.split(','));

And to get the selected values in the same format:

values = $('#strings').val();
PostureOfLearning
  • 3,403
  • 3
  • 23
  • 44
10

Pure JavaScript ES6 solution

  • Catch every option with a querySelectorAll function and split the values string.
  • Use Array#forEach to iterate over every element from the values array.
  • Use Array#find to find the option matching given value.
  • Set it's selected attribute to true.

Note: Array#from transforms an array-like object into an array and then you are able to use Array.prototype functions on it, like find or map.

var values = "Test,Prof,Off",
    options = Array.from(document.querySelectorAll('#strings option'));

values.split(',').forEach(function(v) {
  options.find(c => c.value == v).selected = true;
});
<select name='strings' id="strings" multiple style="width:100px;">
    <option value="Test">Test</option>
    <option value="Prof">Prof</option>
    <option value="Live">Live</option>
    <option value="Off">Off</option>
    <option value="On">On</option>
</select>
Mariano Desanze
  • 7,205
  • 4
  • 39
  • 65
kind user
  • 32,209
  • 6
  • 49
  • 63
2

Basically do a values.split(',') and then loop through the resulting array and set the Select.

buydadip
  • 7,310
  • 14
  • 63
  • 127
kashipai
  • 149
  • 2
  • 13
1
var groups = ["Test", "Prof","Off"];

    $('#fruits option').filter(function() {
      return groups.indexOf($(this).text()) > -1; //Options text exists in array
    }).prop('selected', true); //Set selected
bummi
  • 26,435
  • 13
  • 58
  • 97
Member con
  • 29
  • 2
1

Pure JavaScript ES5 solution

For some reason you don't use jQuery nor ES6? This might help you:

var values = "Test,Prof,Off";
var splitValues = values.split(',');
var multi = document.getElementById('strings');

multi.value = null; // Reset pre-selected options (just in case)
var multiLen = multi.options.length;
for (var i = 0; i < multiLen; i++) {
  if (splitValues.indexOf(multi.options[i].value) >= 0) {
    multi.options[i].selected = true;
  }
}
<select name='strings' id="strings" multiple style="width:100px;">
    <option value="Test">Test</option>
    <option value="Prof">Prof</option>
    <option value="Live">Live</option>
    <option value="Off">Off</option>
    <option value="On" selected>On</option>
</select>
Mariano Desanze
  • 7,205
  • 4
  • 39
  • 65
-1

this is error in some answers for replace |

var mystring = "this|is|a|test";
mystring = mystring.replace(/|/g, "");
alert(mystring);

this correction is correct but the | In the end it should look like this \|

var mystring = "this|is|a|test";
mystring = mystring.replace(/\|/g, "");
alert(mystring);
Caconde
  • 2,969
  • 7
  • 24
  • 27