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!!!
Iterate through the loop using the value in a dynamic selector that utilizes the attribute selector.
Working Example http://jsfiddle.net/McddQ/1/
in jQuery:
or in pure JavaScript:
jQuery does significant abstraction here.
Pure JavaScript ES6 solution
querySelectorAll
function and split thevalues
string.Array#forEach
to iterate over every element from thevalues
array.Array#find
to find the option matching given value.selected
attribute totrue
.Note:
Array#from
transforms an array-like object into an array and then you are able to useArray.prototype
functions on it, like find or map.Pure JavaScript ES5 solution
For some reason you don't use jQuery nor ES6? This might help you:
Just provide the jQuery val function with an array of values:
And to get the selected values in the same format:
Basically do a values.split(',') and then loop through the resulting array and set the Select.