Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to Select Multiple options [closed]

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?

like image 323
Dave Hunt Avatar asked Aug 18 '09 19:08

Dave Hunt


People also ask

How do you select multiple options in JavaScript?

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.

How do I select multiple options in HTML?

For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.


1 Answers

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.

like image 70
Peter Bailey Avatar answered Sep 20 '22 22:09

Peter Bailey