I have a form with a select box that allows multiple options. After a user saves these options, it stores them in a database table.
I can then read this database table to get the options they chose one again. I need to be able to grab this data from the database, put it into an array, then have the options in that select box to be pre-selected when they go to “Edit” their options.
Reading the data into an array is fine, and I know how to make a single option selected within a select box, however I’m not sure how to handle multiple options being selected in javascript.
Can someone help me figure out the javascript required to do this?
Advertisement
Answer
A pure javascript solution
JavaScript
x
21
21
1
<select id="choice" multiple="multiple">
2
<option value="1">One</option>
3
<option value="2">two</option>
4
<option value="3">three</option>
5
</select>
6
<script type="text/javascript">
7
8
var optionsToSelect = ['One', 'three'];
9
var select = document.getElementById( 'choice' );
10
11
for ( var i = 0, l = select.options.length, o; i < l; i++ )
12
{
13
o = select.options[i];
14
if ( optionsToSelect.indexOf( o.text ) != -1 )
15
{
16
o.selected = true;
17
}
18
}
19
20
</script>
21
Although I agree this should be done server-side.