136

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

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. Commented Apr 18, 2021 at 2:43

10 Answers 10

170

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/

Sign up to request clarification or add additional context in comments.

3 Comments

Thats cool, but how do you say that the selected vlaues should be selected in the "multiple select" with the id=string?
@user1824136 Excellent, Glad I could help someone this morning!
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-liner
166

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.

9 Comments

This worked perfect for me and my 'chosen' selects... have to add all the values at once (just like you say above)
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.
Its working when I am passing string, but not when I am passing array.
Having the same issue; this only works with string values, not arrays (using plain JS, not jQuery).
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');
|
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();

Comments

19

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>

Comments

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

Comments

2

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>

Comments

2

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

Comments

-1

Use this:

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

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

Comments

-1

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.

Comments

-2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.