javascriptjquerymultiple-select

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


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


Solution

  • 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/