Javascript to Select Multiple options

Dave Hunt picture Dave Hunt · Aug 18, 2009 · Viewed 99.3k times · Source

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?

Answer

Peter Bailey picture Peter Bailey · Aug 18, 2009

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.