Javascript/jQuery: Set Values (Selection) in a multiple Select
Asked Answered
W

10

132

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!!!

Wigley answered 16/5, 2013 at 8:48 Comment(1)
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 = $('#<%=hfroles.ClientID %>').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.Modality
B
169

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/

Benzaldehyde answered 16/5, 2013 at 8:53 Comment(3)
Thats cool, but how do you say that the selected vlaues should be selected in the "multiple select" with the id=string?Wigley
@user1824136 Excellent, Glad I could help someone this morning!Benzaldehyde
If we're going to depend on jQuery anyway, much prefer ŁukaszW.pl$('#strings').val(values.split(',')). Without jQuery, ŁukaszW.pl's Plain Old Javascript document.getElementById('strings').value = ["Test", "Prof", "Off"] also accomplishes in a one-linerAlarcon
A
161

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.

Antipole answered 16/5, 2013 at 8:54 Comment(9)
This worked perfect for me and my 'chosen' selects... have to add all the values at once (just like you say above)Vibrate
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.Klingensmith
Its working when I am passing string, but not when I am passing array.Henryhenryetta
Having the same issue; this only works with string values, not arrays (using plain JS, not jQuery).Mikvah
I don't know why, but does not work for me :( It works in console but select list component isn't refreshed. (using bootsrap)Stgermain
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');Unhallow
this even works for checkboxes, the one function for everything. No idea why the answer to do it by hand is acceptedWoolsack
@Woolsack 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.Incriminate
It works, but you have to use <option value="something">something</option> If you don't put the attribute value, it will fail.Melamine
R
26

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();
Rotor answered 24/1, 2014 at 1:32 Comment(0)
C
18

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>
Caboose answered 6/4, 2017 at 12:50 Comment(0)
N
2

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

Noguchi answered 16/5, 2013 at 8:51 Comment(0)
T
2
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
Tweedsmuir answered 17/12, 2015 at 7:0 Comment(0)
C
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>
Corneliacornelian answered 2/11, 2017 at 23:22 Comment(0)
C
0

Use this:

$('#demo').multiselect('select', value);

For multiple values just use a loop For more properties this page is very good

Canady answered 25/1, 2023 at 11:6 Comment(0)
K
0

It's been a long time ago, but for those who are looking for a solution to this issue, I leave the following information;

    //My sample data is json data in array.
    let arrayData = [
        {
            blablabla: 'text1'
            ,value: 'value1'
        },
        {
            blablabla: 'text2'
            ,value: 'value2'
        },
        {
            blablabla: 'text3'
            ,value: 'value3'
        },
        
    ];
    

    for(let i = 0; i < arrayData.length; i++)
    {
        $('#multiSelect').multiSelect('select',arrayData[i].value);
        //I enter the loop and fill the data in order in each loop.
    }

    $('#multiSelect').multiSelect('refresh');
    //At the end of the loop I refresh the related item.
Kattiekatuscha answered 1/10, 2023 at 23:18 Comment(0)
M
-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);
Morly answered 3/10, 2019 at 16:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.