Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  64] [ 5]  / answers: 1 / hits: 121402  / 15 Years ago, tue, august 18, 2009, 12:00:00

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?


More From » forms

 Answers
16

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.


[#98883] Friday, August 14, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaredsages

Total Points: 273
Total Questions: 97
Total Answers: 105

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
jaredsages questions
;