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?
To select multiple options in a drop-down list, use the multiple properties. It allows you to select more than one option while pressing CTRL key.
For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.
A pure javascript solution
<select id="choice" multiple="multiple">
<option value="1">One</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<script type="text/javascript">
var optionsToSelect = ['One', 'three'];
var select = document.getElementById( 'choice' );
for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
o = select.options[i];
if ( optionsToSelect.indexOf( o.text ) != -1 )
{
o.selected = true;
}
}
</script>
Although I agree this should be done server-side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With